简体   繁体   English

如何使用 HTML 按钮暂停 CSS 动画?

[英]How do you pause a CSS animation with an HTML button?

I'm trying to pause a CSS animation with an HTML button click, using JS to carry out the pause.我正在尝试通过单击 HTML 按钮来暂停 CSS 动画,并使用 JS 执行暂停。 So far I've tried to change the animation state using JS but it isn't working - the animation plays through and the button seems to have no effect.到目前为止,我已经尝试使用 JS 更改动画状态,但它不起作用 - 动画播放完毕,按钮似乎没有效果。

Here's my JS snippet:这是我的 JS 片段:

 var sun = document.getElementById("sun"); var sky = document.getElementById("sky"); var pauseBtn = document.getElementById("pauseBtn"); function pauseAnimation(){ if((pauseBtn.clicked) == true){ sun.style.animationPlayState("paused"); sky.style.animationPlayState("paused"); } }
 h2:after { content : ' no css!'; color : red; }
 <h2>no HTML</h2>

Can share more code if necessary, any tips based on what you see with the JS?如有必要,可以分享更多代码,根据您在 JS 中看到的内容,有什么提示吗?

You can add or remove a class name that you define the CSS animation to when you want to pause or resume the animation.当您想要暂停或恢复动画时,您可以添加或删除定义 CSS 动画的类名。

 <style> .sky-animation-class-name { animation: /* animation properties */; } .sun-animation-class-name { animation: /* animation properties */; } </style> <body> <div id="sky" class="sky-animation-class-name"></div> <div id="sun" class="sun-animation-class-name"></div> </body> <script> var sky = document.getElementById("sky"); var sun = document.getElementById("sun"); var pauseBtn = document.getElementById("pauseBtn"); var resumeBtn = document.getElementById("resumeBtn"); function pauseAnimation(){ if((pauseBtn.clicked) == true){ sky.classList.remove("sky-animation-class-name"); sun.classList.remove("sun-animation-class-name"); } } function resumeAnimation(){ if((resumeBtn.clicked) == true){ sky.classList.add("sky-animation-class-name"); sun.classList.add("sun-animation-class-name"); } } </script>

this way这边走

 const sun = document.querySelector('#sun') , btPP = document.querySelector('#PlayPause') ; btPP.onclick = () => { btPP.textContent = sun.classList.toggle('pause') ? 'Play' : 'Pause' }
 article { margin:1em; } #sun{ background-color : orange; color : #fff; margin : auto; margin-left : auto; margin-left : 0; border : 5px dotted yellow; width : 100px; height : 100px; border-radius : 50%; } .pause { animation-play-state: paused; } .animating { animation-name : slide; animation-duration : 3s; animation-timing-function : ease-in; animation-iteration-count : infinite; animation-direction : alternate; } @keyframes slide { from { margin-left : 0 } to { margin-left : 80% } }
 <article> <div id="sun" class="animating"></div> </article> <button id="PlayPause"> Pause</button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM