我使用以下JavaScript代码开始CSS动画(element
是div
,name
是现有规则的名称,destination
是元素应该移至的位置)。第一次调用该函数时,它会按预期工作(div
轻柔地移动到其最终目标)。第二次,它只是跳转到目的地(因为我明确地设置了left
和top
),但没有发生移动。如果我在行中设置了一个断点(名称分配发生在哪里)(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);
}
}
我使用谷歌浏览器
找到解决方案:设置动画名称后,我调用延迟函数,将动画名称重置为“无”。如果名称被清除并设置为一段代码,则浏览器不会识别该更改并且不执行任何操作。 – Gerhard