2012-06-26 44 views
2

嘿,我正在尝试更改div的背景颜色。我写了一个脚本来改变身体的背景颜色。代码如下在某段时间后更改div的背景颜色

<script> 
colors = new Array('black', 'red', 'green'); 
function annoyingEffect(tic){ 
tic %= colors.length; 
document.bgColor = colors[tic]; 
setTimeout("annoyingEffect("+(tic+1)+")", 2000);} 
</script> 
<body onload="annoyingEffect(0)"> 

</body> 

但是,如果我尝试添加一个div并插入的onload =“annoyingEffect(0)”里面的功能,这是行不通的。我错过了什么?

+0

似乎s为我工作:http://jsfiddle.net/FH7Zx/ –

回答

1

Here's an example传递(http://jsfiddle.net/NSJDR/5/ )你如何改变身体和一个<div>

<html> 
    <head> 
     <script type="text/javascript"> 
      colors = new Array('blue', 'red', 'green', 'yellow', 'brown', 'orange'); 

      function annoyingEffect(tic){ 
       tic %= colors.length; 
       document.bgColor = colors[tic]; 
       setTimeout("annoyingEffect("+(tic+1)+")", 1000); 
      } 

      function annoyingEffectOnDiv(tic, divId){ 
       tic %= colors.length; 
       divVar = document.getElementById(divId); 
       divVar.style.background = colors[tic]; 
       setTimeout("annoyingEffectOnDiv("+(tic+1)+", '"+divId+"')", 1000); 
      } 

     </script> 
    </head> 

    <body onload="annoyingEffect(0); annoyingEffectOnDiv(2, 'divtest');"> 
     <div id="divtest"> 
      <label>HELLOOOOOA :D</label> 
     </div> 
    </body> 
</html>​ 
+0

thanx队友中传递函数作为一个字符串,但我必须改变代码以适应我的需要,但它工作完美:-) –

+0

没问题,我很高兴它的工作为雅:) – ClydeFrog

0

我觉得这条线

setTimeout("annoyingEffect("+(tic+1)+")", 2000); 

应该

setTimeout(function(){ annoyingEffect(tic+1); }, 2000); 

功能参数不是作为字符串

+0

你必须在setTimeout – SuperMykEl

0

见演示:http://jsfiddle.net/rathoreahsan/Fr6tW/

添加在您的JS:

document.getElementById('customid').style.background = colors[tic]; \*your div id*\ 

HTML

<body onload="annoyingEffect(0)"> 
    <div id="customid"></div> 
</body> 

的Javascript

colors = new Array('black', 'red', 'green'); 
function annoyingEffect(tic){ 
    tic %= colors.length; 
    //document.bgColor = colors[tic]; 
    document.getElementById('customid').style.background = colors[tic]; 
    setTimeout("annoyingEffect("+(tic+1)+")", 2000);}