2013-02-28 66 views
0

有人能告訴我爲什麼這個代碼不是閃動我的網頁在兩種顏色之間的背景顏色。網頁背景色閃光燈

<script type="text/javascript"> 
function blinkit() { 
    intrvl = 0; 
    for (nTimes = 0; nTimes < 3; nTimes++) { 
     intrvl += 1000; 
     setTimeout("document.bgColor='#0000FF';", intrvl); 
     intrvl += 1000; 
     setTimeout("document.bgColor='#FFFFFF';", intrvl); 
    } 
} 
</script> 
+1

它爲我工作在Firefox。可能是因爲你沒有調用blinkit()函數? – showdev 2013-02-28 20:00:03

+1

你在哪兒叫'blinkit'?你所展示的是被定義的功能,而不是被調用的。 – BLSully 2013-02-28 20:00:17

+0

在身體 – user182 2013-02-28 20:02:54

回答

0

試試這個:

function blinkit() { 
    intrvl = 0; 
    window.setInterval(function(){ 
     intrvl += 1000; 
     setTimeout("document.bgColor='#0000FF';", intrvl); 
     intrvl += 1000; 
     setTimeout("document.bgColor='#FFFFFF';", intrvl); 
    }, intrvl); 
} 
0

從來沒有過字符串setTimeout,因爲它是一樣壞eval

相反,嘗試這樣的事:

function blinkit(times, thenwhat) { 
    var toggle = times*2, timer = setInterval(function() { 
      document.body.style.backgroundColor = toggle%2 ? "#0000FF" : "#FFFFFF"; 
      toggle--; 
      if(!toggle) { 
       clearInterval(timer); 
       thenwhat && thenwhat(); 
      } 
     },1000); 
    return timer; 
} 
var flashy = blinkit(3); 
// The background will flash three times. 
// You can also cancel it with `clearInterval(flashy);` 

與上面的代碼,你也可以告訴它做一些事情的時候,它的完成:

var flashy = blinkit(3,function() {alert("Hello!");});