我想更改 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
存在。
最佳答案
您的错误发生是因为您试图在 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();
};
关于javascript - 如何使用 JavaScript 设置 CSS 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14189019/