CSS 动画只工作一次

CSS animation only working once

本文关键字:一次 动画 工作 CSS      更新时间:2023-09-26

我使用以下JavaScript代码启动CSS动画(element是一个divname是现有规则的名称,destination是元素应该移动到的位置)。第一次调用此函数时,它会按预期工作(div会轻柔地移动到其最终目标)。第二次,它只是跳转到目的地(因为我显式设置了lefttop),但没有发生任何移动。如果我在发生名称分配的行中设置断点(webkitAnimationName),则动画将像第一次一样执行。我需要延迟吗?

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);
  }
}

我正在使用谷歌浏览器

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

#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; } 然后你只需添加和删除"活动"类。菜单将滑动。希望我能帮助你。干杯