温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

CSS3如何实现动画暂停和恢复

发布时间:2025-12-17 00:29:17 来源:亿速云 阅读:121 作者:小樊 栏目:编程语言

在CSS3中,可以使用animation-play-state属性来实现动画的暂停和恢复。这个属性有两个值:running(默认值)和paused。

以下是一个简单的例子:

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CSS3 Animation Pause and Resume</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div class="box"></div>
    <button onclick="pauseAnimation()">Pause</button>
    <button onclick="resumeAnimation()">Resume</button>
</body>
</html>

CSS (styles.css):

.box {
  width: 100px;
  height: 100px;
  background-color: red;
  animation-name: example;
  animation-duration: 4s;
  animation-iteration-count: infinite;
}

@keyframes example {
  from {background-color: red;}
  to {background-color: yellow;}
}

JavaScript:

function pauseAnimation() {
  document.querySelector('.box').style.animationPlayState = 'paused';
}

function resumeAnimation() {
  document.querySelector('.box').style.animationPlayState = 'running';
}

在这个例子中,我们创建了一个名为.box的动画元素,它会在红色和黄色之间无限循环。我们还添加了两个按钮,一个用于暂停动画,另一个用于恢复动画。

当点击"Pause"按钮时,pauseAnimation()函数会被调用,将.box元素的animation-play-state属性设置为paused,从而暂停动画。当点击"Resume"按钮时,resumeAnimation()函数会被调用,将.box元素的animation-play-state属性设置为running,从而恢复动画。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI
助
手