使用事件侦听器(Javascript,jQuery)将BG颜色更改为随机颜色?



我正在尝试一个简单的随机背景颜色生成器。当用户单击按钮时,背景颜色将更改为随机 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;
} 

作为奖励,下面是实现 randojs.com 的代码的简化版本:

var button = document.getElementById("press");
button.addEventListener("click", randomBgColor);
function randomBgColor() {
var bgColor = 'rgb(' + rando(255) + ',' + rando(255) + ',' + rando(255) + ')';
document.body.style.background = bgColor;
button.style.backgroundColor = bgColor;
}
<script src="https://randojs.com/1.0.0.js"></script>
<button id="press">Change color!</button>

最新更新