【问题标题】:Why animation play state is always running?为什么动画播放状态总是running?
【发布时间】:2017-12-12 08:07:32
【问题描述】:

即使在使用 animation-iteration-count1animation-fill-modeforwards 之后,我也无法使用 css3 动画将动画播放状态设为 paused

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 似乎没有将播放状态设置为暂停。总结这个问题没有发现或解决方案?

【问题讨论】:

  • 但是我在我的 sn-p 中看不到控制台。任何人都可以修复 sn-p 以显示控制台。谢谢。
  • 我无需编辑即可运行它。
  • 哦,那它可能没有在 linux chromium 浏览器中显示...
  • 没问题。 :-)
  • 控制台是作为div实现的,所以会受到动画的影响。解决方案是不使用像 div 这样的通用选择器。给你的 div 一个 id 什么的。

标签: javascript css css-animations


【解决方案1】:

一旦动画完成所有迭代,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 时,我真的看不出有任何理由这样做。

【讨论】:

    【解决方案2】:

    我不知道为什么 css3 将动画播放状态保持在 running 而是使用 animationend 事件:

    var x = document.getElementById("myDIV");
    x.addEventListener("animationend", function(){
      console.log('paused'); // animation is end
    });
    

    这里是animationend的参考:https://developer.mozilla.org/en-US/docs/Web/Events/animationend

    【讨论】:

      猜你喜欢
      • 2018-08-19
      • 2015-08-31
      • 2020-07-28
      • 2015-12-24
      • 2021-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多