簡體   English   中英

使用setInterval更改文本字段的顏色;

[英]changing text fields color using setInterval;

當我單擊按鈕時,我想更改文本字段的背景顏色,並且在一定時間后,閃爍應停止/

我嘗試了在setInterval中使用setTimeout進行實驗,結果如下:

 var interval; function myFunction2(){ interval = setInterval(function(){myFunction()}, 500); } function myFunction() { var x = document.getElementById("blink"); x.style.backgroundColor = x.style.backgroundColor == "white" ? "blue" : "white"; setTimeout(function(){clearInterval(interval);}, 1500); } 
 <html> <head> <title>blink</title> </head> <body> <input type="text" id="blink" value="blinking!" style="background: white;"> <button type="button" id="blinkbtn" onclick="myFunction2();">click!</button> </body> </html> 

這段代碼中有2個問題,盡管有時背景會卡在藍色上,但我不希望這樣。 第二個問題是在第一次運行功能后(按下按鈕時),您需要雙擊按鈕才能再次運行功能。

使用css作為閃爍動畫,並使用javascript的setTimeout添加類.blink ,並在x.blink其刪除:

 function myFunction2() { const x = document.getElementById("blink") x.classList.add('blink') setTimeout(function() { x.classList.remove('blink') }, 1000) } 
 .blink { animation: blink .1s linear infinite; } @keyframes blink { from { background: #fff; } to { background: blue; } } 
 <input type="text" id="blink" value="blinking!" style="background: white;"> <button type="button" id="blinkbtn" onclick="myFunction2();">click!</button> 

您在哪里設置超時3次(每次調用間隔函數)

這個版本解決了您的問題:

 var interval, timeout; var x = document.getElementById("blink"); function clear(){ if(interval){ clearInterval(interval); console.log("clear interval"); } if(timeout){ clearInterval(timeout); console.log("clear timeout"); x.style.backgroundColor = "white"; } } function myFunction2(){ clear(); interval = setInterval(myFunction, 500); timeout = setTimeout(clear, 2050); //4x500 + a little delay to ensure the 4 times run } function myFunction() { x.style.backgroundColor = x.style.backgroundColor == "white" ? "blue" : "white"; } 
 <html> <head> <title>blink</title> </head> <body> <input type="text" id="blink" value="blinking!" style="background: white;"> <button type="button" id="blinkbtn" onclick="myFunction2();">click!</button> </body> </html> 

暫無
暫無

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

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