animation-play-state属性可控制CSS动画的播放与暂停,其值为running或paused。通过JavaScript或CSS类动态切换该属性,能实现鼠标悬停等交互场景下的动画暂停与恢复,操作简单高效。

在HTML和CSS中,控制动画的播放与停止主要通过 animation-play-state 属性实现。这个属性可以动态地暂停或继续运行CSS动画,非常适合用于交互场景,比如鼠标悬停时暂停动画。
CSS中的 animation-play-state 支持两个值:
你可以为任意应用了CSS动画的元素设置该属性来控制其状态。
例如,有一个持续旋转的盒子:
立即学习“前端免费学习笔记(深入)”;
<div style="width:50px; height:50px; background:red; animation: spin 2s linear infinite;"></div>
<style>
@keyframes spin {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
.animated-box {
width: 50px;
height: 50px;
background: red;
animation: spin 2s linear infinite;
}
.animated-box.paused {
animation-play-state: paused;
}
</style>
此时,给元素添加 .paused 类即可暂停动画:
// 暂停动画document.querySelector('.animated-box').classList.add('paused');document.querySelector('.animated-box').classList.remove('paused');你也可以直接使用JavaScript修改 animationPlayState 样式属性:
const box = document.querySelector('.animated-box');
// 暂停动画
box.style.animationPlayState = 'paused';
// 恢复播放
box.style.animationPlayState = 'running';
这种方式适合绑定事件,比如鼠标移入暂停、移出恢复:
box.addEventListener('mouseenter', () => {
box.style.animationPlayState = 'paused';
});
box.addEventListener('mouseleave', () => {
box.style.animationPlayState = 'running';
});
基本上就这些。利用 animation-play-state 能轻松实现对CSS动画的暂停与恢复,无需重写关键帧或重置动画,简单高效。
以上就是html 如何停止动画_HTML动画停止(animation-play-state)控制方法的详细内容,更多请关注php中文网其它相关文章!
HTML怎么学习?HTML怎么入门?HTML在哪学?HTML怎么学才快?不用担心,这里为大家提供了HTML速学教程(入门课程),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号