2

嘿,我正在尝试更改 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)" 函数,它就不起作用。我错过了什么?

4

3 回答 3

1

这是一个示例(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>​
于 2012-06-26T12:35:35.700 回答
0

我认为这条线

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

应该

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

函数参数不作为字符串传递

于 2012-06-26T12:34:19.010 回答
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);} 
于 2012-06-26T12:35:37.897 回答