控制CSS动画播放与暂停

发布时间:2026/7/29 19:04:31

控制CSS动画播放与暂停 在日常的动画开发过程中经常遇到需要暂停/继续播放动画的场景。要控制CSS动画的播放与暂停核心是使用 animation-play-state 属性并通过JavaScript动态切换其值。通过js控制css除了直接操作DOM以外比较常用的方法是使用CSS变量示例CSS动画.box{width:100px;height:100px;background-color:#3498db;animation:bounce 2s infinite alternate;/* 定义动画 */animation-play-state:var(--animationPlayState);}keyframesbounce{from{transform:translateY(0);}to{transform:translateY(-20px);}}通过按钮点击实现动画暂停/播放import{useState}fromreact;import./styles.css;exportdefaultfunctionApp(){const[animationPlayState,setAnimationPlayState]useState(running);constonClick(){setAnimationPlayState(animationPlayStatepaused?running:paused);};return(div classNameboxstyle{{--animationPlayState:animationPlayState,}}/button onClick{onClick}/button/);}

相关新闻