css3动画暂停主要用到animation-play-state属性。
animation-play-state CSS 属性定义一个动画是否运行或者暂停。可以通过查询它来确定动画是否正在运行。另外,它的值可以被设置为暂停和恢复的动画的重放。
恢复一个已暂停的动画,将从它开始暂停的时候,而不是从动画序列的起点开始在动画。
MDN官方介绍链接点击查看属性详情
先看效果图
复制下面demo查看具体效果
主要是js代码
<div class='box'></div>
<button id='play'>播放</button>
<button id='stop'>暂停</button>
<style>
.box {
width: 100px;
height: 100px;
background-color: red;
animation: boxanimation 3s linear infinite;
}
@keyframes boxanimation {
0% {
transform: translateX(0)
}
50% {
transform: translateX(300px)
}
100% {
transform: translateX(0)
}
}
</style>
<script>
document.querySelector('#play').onclick = () => {
document.querySelector('.box').style.animationPlayState = '' // animationPlayState 为空时继续播放
}
document.querySelector('#stop').onclick = () => {
document.querySelector('.box').style.animationPlayState = 'paused' // animationPlayState 为paused时暂停
console.log(document.querySelector('.box'));
}
</script>