gpt4 book ai didi

javascript - 如何使用 JavaScript 设置 CSS 值?

转载 作者:行者123 更新时间:2023-11-29 16:16:53 25 4
gpt4 key购买 nike

我想更改 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();
};

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

关于javascript - 如何使用 JavaScript 设置 CSS 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14189019/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com