控制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}from"react";import"./styles.css";exportdefaultfunctionApp(){const[animationPlayState,setAnimationPlayState]=useState("running");constonClick=()=>{setAnimationPlayState(animationPlayState==="paused"?"running":"paused");};return(<><div className="box"style={{"--animationPlayState":animationPlayState,}}/><button onClick={onClick}></button></>);}