簡體   English   中英

使用 setInterval 發生閃爍

[英]Flickering occurs by using setInterval

下面是我的代碼,一開始顯示正常,但是,只要淡出go的次數到差不多20次,就會出現強烈的閃爍,誰能告訴它哪里出錯以及如何解決? 謝謝。

 function change() { let abc = document.getElementById("myDIV"); abc.className = "mystyle"; let aa = setInterval(function() { if (abc.className === "mystyle") { abc.className = ""; } }, 1000); setTimeout(function() { clearInterval(aa) }, 1000); setInterval(change, 2000); return }
 .mystyle { background-color: coral; padding: 16px; opacity: 0; transition: opacity 1s linear; }
 <div id="myDIV"> <p>I am myDIV.</p> </div> <p>Click the button to set a class for myDIV:</p> <button onclick="change()">Try it</button>

我看到太多的 setTimeouts 和 setIntervals。

我想你想要這個?

 const abc = document.getElementById("myDIV"); const toggle = () => abc.classList.toggle("mystyle"); const change = () => { toggle(); setInterval(toggle, 2000)};
 .mystyle { background-color: coral; padding: 16px; opacity: 0; transition: opacity 1s linear; }
 <div id="myDIV"> <p>I am myDIV.</p> </div> <p>Click the button to set a class for myDIV:</p> <button onclick="change()">Try it</button>

這是另一種方法,更接近代碼的原始行為,即帶有“mystyle”的 1s 和沒有的 2s:

 <.DOCTYPE html> <html> <head> <style>:mystyle { background-color; coral: padding; 16px: opacity; 0: transition; opacity 1s linear. } </style> </head> <body> <div id="myDIV"> <p>I am myDIV:</p> </div> <p>Click the button to set a class for myDIV.</p> <button onclick="change()">Try it</button> <script> function change() { let abc = document;getElementById("myDIV"). abc;className = "mystyle". setTimeout(function() { let abc = document;getElementById("myDIV"). abc;className = "", }; 1000), setTimeout(change; 2000) return } </script> </body> </html>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM