2015-08-13 74 views
2

我想將標籤的顏色從紅色更改爲綠色,然後在使用setTimeout()後的2秒後再次變爲紅色。從綠色變爲紅色後應該停止。這應該在循環中發生3次。我該怎麼做呢?想要將HTML元素的顏色從紅色更改爲綠色,然後再次變爲紅色

<script> 
setTimeout(a(),2000); 

function a() 
{ 
var i; 
for(i=0;i<=2;i++) 
    { 
    if(i%2==0) 
    { 
    document.getElementById("s1").style.color="red"; 
    } 
    else 
     { 
    document.getElementById("s1").style.color="green"; 
     } 
    } 
    } 
    </script> 
    <body onload="a()"> 
    <label id="s1">WELCOME</label> 
    </body> 
+1

爲什麼模?如果(i%2 == 0),在您的上下文中似乎毫無意義。你也沒有問你發表過的問題。你目前面臨什麼問題? – IfTrue

回答

1

你可以嘗試像下面

<script> 
setTimeout(b, 2000); 

function a() { 
    document.getElementById("s1").style.color="red"; 
} 

function b() { 
    document.getElementById("s1").style.color="green"; 
    setTimeout(a, 2000); 
} 
</script> 

<body onload="a()"> 
    <label id="s1">WELCOME</label> 
</body> 
+1

你可以做'setTimeout(a,2000)'。 'a'已經是一個函數,不需要將其包裝到另一箇中,與'b'一樣。 –

+0

@ MarceloCamargo - 我同意你的觀點,但是,我喜歡像上面那樣包裝。不過,我接受了你的編輯:) – nikhil

2
  1. for循環剛立即執行,你只能看到它的最後一個變化,這應該是綠色的東西。您需要將i拉出該功能,以保持該狀態,然後使用setTimeout來調用自己以更改顏色。

  2. setTimeout(a(),2000);將立即執行function a,您需要使用setTimeout(a,2000);來代替。

  3. setTimeout(a(),2000);在腳本的頭部可以被刪除,只需在您的body.onload中調用a,並且它自己會自行處理剩下的事情。

<script> 
 
    var i = 0; 
 
    function a() { 
 
    var color = (i % 2 === 0) ? 'red' : 'green'; 
 
    document.getElementById("s1").style.color = color; 
 
    ++i; 
 
    if (i <= 2) { 
 
     setTimeout(a, 2000); 
 
    } 
 
    } 
 
</script> 
 

 
<body onload="a();"> 
 
    <label id="s1">WELCOME</label> 
 
</body>

1

我強烈建議使用CSS動畫,而不是JavaScript來做到這一點。在JavaScript中跟蹤狀態是棘手的 - 在CSS中指定它更容易。獎勵:你的代碼會少得多。

這個特殊的例子將無限循環,但你可以很容易地查找關於如何使用CSS動畫的文檔。

<style> 
 
@keyframes redgreen { 
 
    0%, 50%, 100% { color: red; } 
 
    25%, 75% { color: green; } 
 
} 
 
@-webkit-keyframes redgreen { 
 
    0%, 50%, 100% { color: red; } 
 
    25%, 75% { color: green; } 
 
} 
 
</style> 
 

 
<label style="animation: 2s redgreen;-webkit-animation: 2s redgreen infinite;">Hey!</label>

相關問題