开发者

What is the syntax for document.body.style.backgroundColor?

I am a JavaScript newbie. I have the following code and it is behaving very strangely. What it is supposed to do is originally set the background color to red, then cycle through a series of background colors after an alert dialogue is cleared. Color names are currently in string formats, but the same behavior results if I use the hex IDs.

Usually, when the page is loaded, it starts off coloring the body red like it is supposed to. The first alert clear sometimes changes the background to orange, sometimes not, then there is no change as the next dialogues (yellow, green, blue, indigo, black) are cleared until the last color change, which sometimes takes and sometimes doesn't.

<html>
<head>
<title>Color Flasher</title>
</head>

<body>

<script type="text/javascript">
    function color1() {
        document.body.style.backgroundColor = 'red';
    }

    function color2() {
        document.body.style.backgroundColor = 'orange';
    }

    function color3() {
        document.body.style.backgroundColor = 'yellow';
    }

    function color4() {
        document.body.style.backgroundColor = 'green';
    }

    function color5() {
        document.body.style.backgroundColor = 'blue';
    }

    function color6() {
        document.body.style.backgroundColor = 'i开发者_Go百科ndigo';
    }

    function color7() {
        document.body.style.backgroundColor = 'black';
    }

    function color8() {
        document.body.style.backgroundColor = 'violet';
    }

    color1();

    alert("ready for another color? - orange");
    color2();

    alert("ready for another color? - yellow");
    color3();

    alert("ready for another color? - green");
    color4();

    alert("ready for another color? - blue");
    color5();

    alert("ready for another color? - indigo");
    color6();

    alert("ready for another color? - black");
    color7();

    alert("ready for another color? - violet");
    color8();
</script>

<center>
<h1>Color Flasher<br></h1>
</center>
<hr>
</body>
</html>

Can someone explain where I'm getting the syntax wrong?


You should try placing your <script> in the <head> or if you really want your script in the body tag, you should place before the closing </body> tag.

FYI it works fine on my side. Tested on JSFiddle and they automatically place the <script> in the body tag.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜