当我无法设置 CSS 动画时,如何触发“animationend”事件?

BOZ*_*BOZ 8 javascript dom-events css-animations

如果我将 css 动画设置为“元素”,就可以了。如果 Css 动画不可用,它如何像 ES5 中的零秒动画一样触发?

function run() { ... }

element.addEventListener('animationend', run);
Run Code Online (Sandbox Code Playgroud)

回复

@Anurag Srivastava,

我是错误的想法还是我有以下代码错误?无论哪种方式,返回值都是“”。

function run() { ... }

element.addEventListener('animationend', run);
Run Code Online (Sandbox Code Playgroud)
var el1 = document.getElementById("notAnimation");

console.log(el1.style.animation);

var el2 = document.getElementById("onAnimation");

console.log(el2.style.animation);
Run Code Online (Sandbox Code Playgroud)
div {
  padding: 10px;
  margin: 20px;
}

#notAnimation {}

#onAnimation {
  animation: scale 10s ease-in-out;
}

@keyframes scale {
    0% {
      transform: scale(1);
      opacity: 1;
      color: black;
    }
    50% {
      transform: scale(0.95);
      opacity: .4;
      color: red;
    }
    100% {
      transform: scale(1);
      opacity: 1;
      color: black;
    }
}
Run Code Online (Sandbox Code Playgroud)

Anu*_*ava 2

您可以检查element.style.WebkitAnimation和是否element.style.animation包含任何值,run()如果值为“”则执行

编辑事实证明,.style任何值都会返回“”。你需要的是window.getComputedStyle()连同财产animationName。如果是none,则没有动画,否则有。检查下面的代码:

var el1 = document.getElementById("notAnimation");
console.log(window.getComputedStyle(el1)["animationName"])

var el2 = document.getElementById("onAnimation");
console.log(window.getComputedStyle(el2)["animationName"])
Run Code Online (Sandbox Code Playgroud)
div {
  padding: 10px;
  margin: 20px;
}

#notAnimation {}

#onAnimation {
  animation: scale 10s ease-in-out;
}

@keyframes scale {
  0% {
    transform: scale(1);
    opacity: 1;
    color: black;
  }
  50% {
    transform: scale(0.95);
    opacity: .4;
    color: red;
  }
  100% {
    transform: scale(1);
    opacity: 1;
    color: black;
  }
}
Run Code Online (Sandbox Code Playgroud)
<div id="notAnimation">
  Not Animation
</div>

<div id="onAnimation">
  Animation
</div>
Run Code Online (Sandbox Code Playgroud)

  • 仅当没有设置动画时才会返回“”,否则返回一个字符串,例如。“myAnim 2s escape-in​​” 另外,您需要检查 .animation 和 .WebkitAnimation (2认同)