0

我正在尝试将变色属性附加到表格背景。

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">

但我无法让它工作,任何帮助将不胜感激。提前谢谢

4

2 回答 2

2

您必须将您的 javascript 放在您的元素(您的表格)下:

<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>
于 2013-10-28T19:43:42.397 回答
2

DOM 尚未加载。你可以做这样的事情......

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

或者在你的 body 标签中放置一个处理程序:

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

哦,您可以这样收听该事件DOMContentLoaded

document.addEventListener("DOMContentLoaded", function(event) {
    var bakgrunnFarge=new Array("#CCFFCC", "#FFCCCC")
    document.getElementById("change_color").style.background=bakgrunnFarge[Math.floor(Math.random()*bakgrunnFarge.length)]
});
于 2013-10-28T20:10:02.703 回答