2015-01-16 80 views
0

我使用以下JavaScript代码开始CSS动画(elementdiv,name是现有规则的名称,destination是元素应该移至的位置)。第一次调用该函数时,它会按预期工作(div轻柔地移动到其最终目标)。第二次,它只是跳转到目的地(因为我明确地设置了lefttop),但没有发生移动。如果我在行中设置了一个断点(名称分配发生在哪里)(webkitAnimationName),则会首次执行动画。我需要延迟吗?只能使用一次的CSS动画

function flyTo(element, name, destination) { 
    var rule = findKeyframesRule(name); 
    if (rule != null) { 
    element.style.webkitAnimationName = "none"; 

    // remove the existing 0% and 100% rules 
    rule.deleteRule("from"); 
    rule.deleteRule("to"); 

    // create new 0% and 100% rules 
    rule.insertRule("from {top: " + element.style.top + "; left: " + element.style.left + ";}"); 
    rule.insertRule("to {top: " + px(destination.y) + "; left: " + px(destination.x) + ";}"); 

    // assign the animation to our element (which will cause the animation to run) 
    element.style.left = px(destination.x); 
    element.style.top = px(destination.y); 
    element.style.webkitAnimationDuration = "1s"; 
    element.style.webkitAnimationTimingFunction = "linear"; 
    element.style.webkitAnimationName = name; 
    } else { 
    element.style.left = px(destination.x); 
    element.style.top = px(destination.y); 
    } 
} 

我使用谷歌浏览器

+0

找到解决方案:设置动画名称后,我调用延迟函数,将动画名称重置为“无”。如果名称被清除并设置为一段代码,则浏览器不会识别该更改并且不执行任何操作。 – Gerhard

回答

0

我不知道哪里在代码中的错误是。但我尝试给你另一个(在我看来更好的解决方案)。我的一个滑动菜单的代码示例:

#tag-menu { top: 0px; width: 270px; height: 100%; left: -370px; background: #2F535C; z-index: 9; box-shadow: 5px 5px 10px 0px rgba(84,84,84,0.25); position: fixed; display: block; transition: left 0.25s ease-out; -webkit-transition: all 0.2s ease-out; -moz-transition: all 0.2s ease-out; -o-transition: all 0.2s ease-out; -webkit-transform: translateX(-317px); -moz-transform: translateX(-317px); -o-transform: translateX(-317px); -ms-transform: translateX(-317px); } #tag-menu.active{ left:0; -webkit-transform: translateX(0px); -moz-transform: translateX(0px); -o-transform: translateX(0px); -ms-transform: translateX(0px); transform:translateX(0px); transition:all 0.2s ease-in; -webkit-transition: all 0.2s ease-in; -moz-transition: all 0.2s ease-in; -o-transition: all 0.2s ease-in; } 然后你刚刚添加和删除“积极”级。菜单将滑动。希望我能帮助你。 干杯

+1

我想,会有同样的问题:在删除和添加类之间,必须有一些时间,所以浏览器识别这个改变并开始动画(或转换)。我在我的问题中添加了“解决方案”评论。这样它就可以处理我的代码。 – Gerhard