如何用JavaScript设置CSS值?

时间:2013-01-07 02:20:43

标签: javascript dom

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

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 

我确定ID foo存在。

2 个答案:

答案 0 :(得分: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/

答案 1 :(得分: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();
};