css3 動畫的播放、暫停和重新開始


播放

  先在@keyframes中創建動畫,之后把它捆綁到某個選擇器,就可以產生動畫效果。
html

<div id="box" class="box"></div> 

css

@keyframes mymove {
    0% {
      margin-left: 0px;
    }
    50% {
      margin-left: 400px;
    }
    100% {
      margin-left: 0px;
    }
  }
.box {
    margin: 50px 0;
    width: 100px;
    height: 100px;
    background-color: #5578a2;
    animation: mymove 5s infinite ease;
  }

暫停

  我們播放動畫時,如要暫停動畫,就要用到animation-play-state這個屬性。animation-play-state屬性有兩個值:

paused: 暫停動畫;
running: 繼續播放動畫;

當然去掉animation-play-state,也可以繼續播放動畫。

重新開始

  如果要重新開始動畫,加載一個相同的動畫,不同名字,可以達到重新開始動畫的效果。
效果:

效果圖

代碼部分:

html

<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>

css

@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;
  }

js

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;
  });


免責聲明!

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



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