简体   繁体   中英

Change background-color of a table on random with javascript

I'm trying to attach a color-changing property to a table background.

var bakgrunnFarge=new Array("#CCFFCC", "#FFCCCC")
document.getElementById("change_color").style.background=bakgrunnFarge[Math.floor(Math.random()*bakgrunnFarge.length)]

<table class="change_color" name="change_color" id="change_color">

But I just can't get it to work, any help would be much appreciated. In advance, thank you

You have to put your javascript UNDER your elements (your table):

<html>
<head>
    <title>Random background-color</title>
</head>
<body>
    <table class="change_color" name="change_color" id="change_color">
        <tr>
            <td>lorem</td>
            <td>lorem</td>
            <td>lorem</td>
            <td>lorem</td>
        </tr>
        <tr>
            <td>lorem</td>
            <td>lorem</td>
            <td>lorem</td>
            <td>lorem</td>
        </tr>
    </table>

</body>
<script type="text/javascript">
    var bakgrunnFarge=new Array("#CCFFCC", "#FFCCCC");
    window.document.getElementById("change_color").style.background=bakgrunnFarge[Math.floor(Math.random()*bakgrunnFarge.length)]
</script>
</html>

The DOM hasn't loaded yet. You can do something like this...

document.body.onload = function() {
    var bakgrunnFarge=new Array("#CCFFCC", "#FFCCCC")
    document.getElementById("change_color").style.background=bakgrunnFarge[Math.floor(Math.random()*bakgrunnFarge.length)]
}

Or place a handler in your body tag:

<body onload="myFunction()">Stuff</body>

Ooorr you can listen to the event DOMContentLoaded as so:

document.addEventListener("DOMContentLoaded", function(event) {
    var bakgrunnFarge=new Array("#CCFFCC", "#FFCCCC")
    document.getElementById("change_color").style.background=bakgrunnFarge[Math.floor(Math.random()*bakgrunnFarge.length)]
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM