javascript - 为什么动画播放状态一直是running?

标签 javascript css css-animations

即使在使用 animation-iteration-count1animation-fill-modeforwards:

var isRunning = window.getComputedStyle(
  document.querySelector('div')
).getPropertyValue('animation-play-state');

setInterval(function(){
  console.log(isRunning);
},1000)
@keyframes foo {
 0% { 
   width: 0;
 }
 100% {
  width: 50%;
 }
}

div {
 animation: foo 2s linear 0s 1 normal forwards;
 background-color: #f00;
 height: 3px;
}
<div></div>

我应该让animation-play-state在动画结束时被paused


实际上,我提供的以下答案对我不起作用。事实上,我正在使用一个伪元素,而伪元素不接受 addEventListener。因此,我的最终解决方案是仅使用这种方式。

var isRunning = window.getComputedStyle(
      document.querySelector('div'), ':after'
).getPropertyValue('animation-play-state');

遗憾的是,CSS 似乎没有在动画结束时将播放状态设置为暂停。总结这个问题没有发现或解决方案?

最佳答案

一旦动画完成所有迭代,animation-play-state 的值就不会改变。

您需要监听 animationend 事件并手动更改值:

document.querySelector('div').addEventListener('animationend', function() {
  this.style.animationPlayState = 'paused';
  console.log(window.getComputedStyle(this).getPropertyValue('animation-play-state'));
});
@keyframes foo {
 0% { 
   width: 0;
 }
 100% {
   width: 50%;
 }
}

#foo {
 animation: foo 2s linear 0s 1 normal forwards;
 background-color: #f00;
 height: 3px;
}
<div id=foo></div>

...尽管当您的 animation-fill-mode 已经设置为 forwards 时,我真的看不出有任何理由这样做。

关于javascript - 为什么动画播放状态一直是running?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47767859/

相关文章:

javascript - document.write 在 Youtube videobar 的 javascript 中表现异常

javascript - 使用 WebGL 的 Sprite Animation 如何工作?

javascript - 如何在不重新编码的情况下扩大我的网站

javascript - 在 Codepen 中工作的 JS 在我的 html 页面上不起作用

html - 使用 CSS3 为盒子制作动画

javascript - 如何将 $.each 对象转换为数组

javascript - 如何使提交按钮成为 href 和图像

iphone - iPhone Safari 上的定位和字体大小问题

javascript - jQuery 取消先前排队的事件处理程序以重新启动 CSS 动画

html - 无法使用CSS动画垂直翻转导航栏菜单文本