在编写CSS动画时,我们可能会遇到让动画停下来的需求。下面,我们就来介绍一种点击按钮让CSS动画停下来的方法。 .box { width: 100px; height: 100px; backgrou...
在编写CSS动画时,我们可能会遇到让动画停下来的需求。下面,我们就来介绍一种点击按钮让CSS动画停下来的方法。
<style>
.box {
width: 100px;
height: 100px;
background-color: #f00;
animation-duration: 2s;
animation-name: move;
animation-iteration-count: infinite;
}
@keyframes move {
0% { transform: translateY(0); }
100% { transform: translateY(100px); }
}
.stop {
width: 50px;
height: 50px;
background-color: #0f0;
cursor: pointer;
}
</style>
<div class="box"></div>
<div class="stop" onclick="stopAnimation()"></div> 在上面的代码中,我们定义了一个名为move的动画,并将其绑定到.box元素上。同时,我们也定义了一个.stop元素用于触发停止动画的事件,在 HTML 中,我们将这个事件绑定到了一个名为stopAnimation()的函数上。
<script>
function stopAnimation() {
var box = document.querySelector('.box');
box.style.animationPlayState = 'paused';
}
</script> 在JavaScript代码中,我们获取到了CSS动画所在的.box元素,并为其设置了一个animation-play-state属性。这个属性用于控制动画的状态,paused表示停止。
这样,当我们点击.stop元素时,CSS动画就会停止了。