html 如何停止动画_HTML动画停止(animation-play-state)控制方法

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

html 如何停止动画_HTML动画停止(animation-play-state)控制方法

html和CSS中,控制动画的播放与停止主要通过 animation-play-state 属性实现。这个属性可以动态地暂停或继续运行css动画,非常适合用于交互场景,比如鼠标悬停时暂停动画。

animation-play-state 基本语法

CSS中的 animation-play-state 支持两个值:

  • running:动画正常播放(默认状态)
  • paused:动画暂停,当前帧保持显示

你可以为任意应用了CSS动画的元素设置该属性来控制其状态。

如何用CSS暂停动画

例如,有一个持续旋转的盒子:

立即学习前端免费学习笔记(深入)”;

html 如何停止动画_HTML动画停止(animation-play-state)控制方法

万兴爱画

万兴爱画AI绘画生成工具

html 如何停止动画_HTML动画停止(animation-play-state)控制方法 52

查看详情 html 如何停止动画_HTML动画停止(animation-play-state)控制方法

 <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动态控制动画状态

你也可以直接使用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动画的暂停与恢复,无需重写关键帧或重置动画,简单高效。

以上就是

上一篇
下一篇
text=ZqhQzanResources