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

转载于:https://www.cnblogs.com/yangrenmu/p/7085815.html

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值