我正在尝试一个简单的随机背景颜色生成器。当用户单击按钮时,背景色将更改为随机RGB值。但是,我还希望单击按钮时按钮本身可以更改为该随机颜色。
我曾尝试将DOM机械手放入事件监听器和随机RGB函数中。但是我一直收到此错误消息:
script.js:19 Uncaught TypeError: Cannot set property 'backgroundColor' of undefined
at randomBgColor (script.js:19)
at HTMLButtonElement.<anonymous> (script.js:7)
randomBgColor @ script.js:19
(anonymous) @ script.js:7
代码如下:
<html>
<button id="press" class="button">Press me to change the background color!</button>
</html>
var changeColor = document.getElementById("press");
var button = document.getElementsByClassName("button");
changeColor.addEventListener("click", function(){
randomBgColor();
})
function randomBgColor() {
var x = Math.floor(Math.random() * 256);
var y = Math.floor(Math.random() * 256);
var z = Math.floor(Math.random() * 256);
var bgColor = 'rgb(' + x + ',' + y + ',' + z + ')';
console.log(bgColor);
document.body.style.background = bgColor;
button.style.backgroundColor = bgColor;
}
在您的代码中,changeColor
是按钮。将该变量名称重构为button
,如下所示:
var button = document.getElementById("press");
button.addEventListener("click", function(){
randomBgColor();
})
function randomBgColor() {
var x = Math.floor(Math.random() * 256);
var y = Math.floor(Math.random() * 256);
var z = Math.floor(Math.random() * 256);
var bgColor = 'rgb(' + x + ',' + y + ',' + z + ')';
console.log(bgColor);
document.body.style.background = bgColor;
button.style.backgroundColor = bgColor;
}