首页 > 解决方案 > 使用事件侦听器(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;

} 

标签: javascriptjquerydomeventsrandom

解决方案


在您的代码中,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>


推荐阅读