我的 eventListener 似乎不起作用。
我将按钮放在中间,背景颜色为红色,但是当我尝试单击按钮更改背景颜色时,它不起作用。
提前致谢
HTML:
<head>
<title>Change Background Color</title>
<script src="first.js"></script>
<link rel="stylesheet" href="stuff.css">
</head>
<body>
<button class="btn" id="btn">Click Me</button>
</body>
Javascript:
const colors = ["green", "red", "blue", "yellow"];
const btn = document.getElementById('btn');
const color = document.querySelector('.color');
btn.addEventListener('click', function(){
const randomNumber = 2;
document.body.style.backgroundColor = colors[randomNumber];
color.textContent = colors[randomNumber];
}
);
CSS:
button{
position: absolute;
top: 50%;
left: 50%;
}
body{
background-color: red;
}
答案 0 :(得分:2)
所以,有几件事。
HTML 中没有具有“颜色”类的元素。
其次是您的 randomNumber 并不是真正随机的。不过,我确信您正在实现这一目标。但是,我将在下面的代码段中包含我的如何随机化颜色的版本。
这是一个修复版本:
const colors = ["green", "red", "blue", "yellow"];
const btn = document.getElementById('btn');
const color = document.querySelector('.color');
// This function returns a random number from min to min + range
const getRandomNumber = (min, range) => {
return Math.floor(Math.random() * range + min)
}
btn.addEventListener('click', function() {
const randomNumber = getRandomNumber(0, colors.length);
document.body.style.backgroundColor = colors[randomNumber];
color.textContent = colors[randomNumber];
});
button {
position: absolute;
top: 50%;
left: 50%;
}
body {
background-color: red;
}
.color {
display: inline-block;
background-color: white;
padding: 20px 30px;
}
<button class="btn" id="btn">Click Me</button>
<div class="color">red</div>
答案 1 :(得分:0)
首先,您的 HTML 中没有任何名称为 .color
的类,而且您的 const randomNumber = 2;
看起来不太随机。所以在这里,我通过添加一个带有 color
类的简单 div 为您修复了这两个问题。以及一个简单的数学函数,可以给你一个 0 到 3 之间的随机整数来覆盖你的所有颜色。看看。
const colors = ["green", "red", "blue", "yellow"];
const btn = document.getElementById('btn');
const color = document.querySelector('.color');
btn.addEventListener('click', function() {
const randomNumber = Math.floor(Math.random() * 4)
document.body.style.backgroundColor = colors[randomNumber];
color.textContent = colors[randomNumber];
});
button {
position: absolute;
top: 50%;
left: 50%;
}
body {
background-color: red;
}
<button class="btn" id="btn">Click Me</button>
<div class="color">
Color name will show here
</div>
答案 2 :(得分:0)
.color
的元素,因此您的 color.textContent
将返回 null
。const randomNumber = 2;
这将始终为您提供蓝色,因为它是第三个值 0 => green, 1 => red, 2 => blue
以下应该是你要找的...
const colors = ["green", "red", "blue", "yellow"];
const btn = document.getElementById('btn');
const color = document.querySelector('.color');
btn.addEventListener('click', function() {
let random = colors[~~(Math.random()*colors.length)];
document.body.style.backgroundColor = random;
color.textContent = random;
});
button {
position: absolute;
top: 50%;
left: 50%;
}
body {
background-color: red;
}
<div class="color">
</div>
<button class="btn" id="btn">Click Me</button>