本案例围绕着困扰着前端开发都的CSS原生动画的精准控制问题: 让动画可以暂停,然后可以继续进行的问题
代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Animation动画控制</title>
<style>
@keyframes john {
from{
transform: rotate(0deg);
}
to{
transform: rotate(360deg);
}
}
.img{
width: 300px;
height: 300px;
background-color:tomato;
margin: 50px;
display: block;
animation: john 5s infinite linear ;
}
</style>
</head>
<body>
<h1>CSS Animation动画控制</h1>
<button>暂停</button>
<div class="img"></div>
<script>
let img=document.querySelector('.img')
document.querySelector('button').addEventListener('click',function(event){
//核心代码:playState描述着当前动画的状态
let playState=window.getComputedStyle(img).animationPlayState;
if(playState==='running'){
img.style['animation-play-state']="paused"
event.target.innerText="播放"
}else{
img.style['animation-play-state']="running"
event.target.innerText="暂停"
}
})
</script>
</body>
</html>
网友评论