簡體   English   中英

如何使用 HTML 按鈕暫停 CSS 動畫?

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

我正在嘗試通過單擊 HTML 按鈕來暫停 CSS 動畫,並使用 JS 執行暫停。 到目前為止,我已經嘗試使用 JS 更改動畫狀態,但它不起作用 - 動畫播放完畢,按鈕似乎沒有效果。

這是我的 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>

如有必要,可以分享更多代碼,根據您在 JS 中看到的內容,有什么提示嗎?

當您想要暫停或恢復動畫時,您可以添加或刪除定義 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>

這邊走

 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