javascript - 使用事件侦听器(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>
推荐阅读
- c# - 为什么我的代码中的 SQL 命令在运行时被“TODO: FUNC”替换?
- node.js - OAuth2 登录后重定向到前端(在不同的 URL 上)
- ruby - 如何在 IntelliJ 中设置 ruby 分析器
- python - 用整数而不是元组更新列
- java - 给定的工件包含一个带有包引用“android.support.v4.widget”的字符串文字,无法安全地重写
- angular - 触发 Angular 异步 FormGroup 验证
- python - 使用python根据csv中的列分组
- node.js - 如何将 Docker 用于 Windows 内置的 ElectronJS 应用程序?
- unit-testing - 颤振单元测试。运行测试时出错
- python - 为什么TF-IDF的值与IDF_不同?