您的位置:首页 > Web前端 > CSS

css3 动画的播放、暂停和重新开始

2017-11-03 17:33 267 查看


播放

  先在
@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;
});
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  javascript css3 动画