嘿,我正在尝试更改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 =&#34; annoyingEffect(0)&#34;它内部的功能,它不起作用。我错过了什么?
答案 0 :(得分: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>
答案 1 :(得分:0)
我想这一行
setTimeout("annoyingEffect("+(tic+1)+")", 2000);
应该是
setTimeout(function(){ annoyingEffect(tic+1); }, 2000);
函数参数不作为字符串传递
答案 2 :(得分: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);}