2

我想更改 ID 为 .html 的 HTML 元素的背景颜色foo。我目前有这段代码:

var hexcode = new Array('0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f');

// this chooses a random value from the array hexcode
var ranval = function() {
    return hexcode[Math.floor(Math.random()*hexcode.length)];
}

// six ranval() are put together to get color
var colorname = "#" + ranval() + ranval() + ranval() + ranval() + ranval() + ranval();

// trying to put the value on the background of element with "foo" ID.
document.getElementById("foo").style.color = colorname;

此代码引发此错误:

Uncaught TypeError: Cannot read property 'style' of null 

我确定该 IDfoo存在。

4

2 回答 2

4

发生错误是因为您试图在 DOM 准备好之前访问您的元素。在访问之前等待窗口加载:

// Credit: http://paulirish.com/2009/random-hex-color-code-snippets/

function random_color() {
    return '#' + ('00000' + (Math.random() * 16777216 << 0).toString(16)).substr(-6);
}

window.onload = function() {
    document.getElementById("foo").style.backgroundColor = random_color();
};

演示:http: //jsfiddle.net/Blender/xQure/1/

于 2013-01-07T02:26:24.217 回答
2

修复代码的简单方法是:

var random_color = function() {
    function randomHex() {
        return Math.floor(Math.random() * 15).toString(16);
    }
    var str = '#';
    for(var i = 6; i--;) {
        str += randomHex();
    }
    return str;
}


window.onload = function() {
    // For your body background color
    document.body.style.backgroundColor = random_color();

    // For your foo element TEXT color
    document.getElementById("foo").style.color = random_color();

    // For your foo element BACKGROUND color
    document.getElementById("foo").style.backgroundColor = random_color();
};
于 2013-01-07T02:38:54.900 回答