css3动画如何解决动画的播放、暂停和重新开始

0921自我总结

css3如何解决动画的播放、暂停和重新开始

一.解决的本质思路

播放的解决思路

先定义好动画效果通过类名的增加达到样式的出现

暂停的解决思路

我们播放动画时,如要暂停动画,就要用到animation-play-state这个属性。animation-play-state属性有两个值:

paused: 暂停动画;
running: 继续播放动画;

当然去掉animation-play-state,也可以继续播放动画。

重新开始解决思路

播放与重新开始的解决办法

对于元素取多个类名,通过类名的删除,替换

注意点:这里不能删除和添加类名为同一个,而且动画要同一效果,不同动画名称.不然动画效果无法重置

二.演示代码

<div id="box" class="box"></div>
  <p id="text"></p>
  <div class="control">
    <button id="play" value="播放">播放</button>
    <button id="pause" value="暂停">暂停</button>
    <button id="restart" value="重新开始">重新开始</button>
  </div>


<style>
    @keyframes mymove {
    0% {
      margin-left: 0px;
    }
    50% {
      margin-left: 400px;
    }
    100% {
      margin-left: 0px;
    }
  }
  @keyframes mymove1 {
    0% {
      margin-left: 0px;
    }
    50% {
      margin-left: 400px;
    }
    100% {
      margin-left: 0px;
    }
  }
  .box {
    margin: 50px 0;
    width: 100px;
    height: 100px;
    background-color: #5578a2;
  }
  .play {
    animation: mymove 5s infinite ease;
  }
  .restart {
    animation: mymove1 5s infinite ease;
  }
  .pause {
    animation-play-state: paused;
  }
</style>


<script>
var play = document.getElementById('play'),
    pause = document.getElementById('pause'),
    restart = document.getElementById('restart'),
    text = document.getElementById('text'),
    box = document.getElementById('box');
  pause.addEventListener('click', function() {
    if (box.classList.contains('play')) {
      box.className = 'pause play box';
    } else {
      box.className = 'pause restart box';
    }
    text.innerHTML = this.value;
  });
  play.addEventListener('click', function() {
    if (box.classList.contains('play')) {
      box.className = 'play box';
    } else {
      box.className = 'restart box';
    }
    text.innerHTML = this.value;
  });
  restart.addEventListener('click', function() {
    if (box.classList.contains('play')) {
      box.className = 'restart box';
    } else {
      box.className = 'play box';
    }
    text.innerHTML = this.value;
  });
</script>
posted @ 2019-09-21 15:51  小小咸鱼YwY  阅读(3755)  评论(0编辑  收藏  举报