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>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM