如何暂停CSS动画

时间:2018-10-08 20:46:32

标签: html css

我正在尝试使用以下代码暂停由CSS制作的动画,但是它不起作用。我犯什么错误?我该怎么解决?

.paused{
    -webkit-animation-play-state:paused;
    -moz-animation-play-state:paused;
    -o-animation-play-state:paused; 
    animation-play-state:paused;
}
#cube1{

    -webkit-animation: slide 5s forwards 0s 3;
    animation: mcube1 1s forwards 0s 1;
    
}


@-webkit-keyframes mcube1{

    
    to{
        -webkit-transform: translate(130.5px, -77px);
        -ms-transform: translate(130.5px, -77px);
        transform: translate(130.5px, -77px);
    }
}
@keyframes mcube1{


    to{
        -webkit-transform: translate(130.5px, -77px);
        -ms-transform: translate(130.5px, -77px);
        transform: translate(130.5px, -77px);
    }
}
<img  id="cube1" class="position-absolute paused" src="images/intro/1.png">

1 个答案:

答案 0 :(得分:2)

#cube1是比.paused更具体的选择器。因此,您将用简写的animation-play-state声明覆盖animation

您可以添加!important

.paused {
    animation-play-state: paused !important;
}

或使选择器更具体:

#cube1.paused {
    animation-play-state: paused;
}

示例:

document.querySelector('button').addEventListener('click', function() {
  document.getElementById('cube1').classList.toggle('paused')
});
body {
  margin-top: 80px;
}

#cube1.paused {
  -webkit-animation-play-state: paused;
  -moz-animation-play-state: paused;
  -o-animation-play-state: paused;
  animation-play-state: paused;
}

#cube1 {
  -webkit-animation: slide 5s forwards 0s 3;
  animation: mcube1 1s forwards 0s 1;
  animation-iteration-count: infinite;
  animation-direction: alternate;
}

@-webkit-keyframes mcube1 {
  to {
    -webkit-transform: translate(130.5px, -77px);
    -ms-transform: translate(130.5px, -77px);
    transform: translate(130.5px, -77px);
  }
}

@keyframes mcube1 {
  to {
    -webkit-transform: translate(130.5px, -77px);
    -ms-transform: translate(130.5px, -77px);
    transform: translate(130.5px, -77px);
  }
}
<img id="cube1" class="position-absolute paused" src="https://www.fillmurray.com/100/100">

<button type="button">Toggle paused</button>