[英]How do I change the background color using javascript?
我想将背景颜色更改为从数组中随机选择的颜色,但我不确定我在做什么。 我对如何使按钮工作感到困惑。
这是 HTML 的正文,最终我必须将文本更改为它更改为的颜色的名称,但我想先获取颜色:
const colors = ['#e5051b', '#f6e06a', '#f1a432', '#a9b724', '#458a92', '#aa0c90', '#301196d', '#f2b8a2', 'fdbb2f', '27d193']; const randomColor = colors[Math.floor(Math.random() * colors.length)]; let button = document.getElementById('button'); button.addEventListener('click', function changeColor() { const color = randomColor; document.body.style.backgroundColor = `${color}`; });
<body> <div class="box"> <div> <p>Hex color code: #ffffff</p> <button class="button">Change Color</button> </div> </div> </body>
每次点击都必须随机着色
const colors = ['#e5051b', '#f6e06a', '#f1a432', '#a9b724', '#458a92', '#aa0c90', '#301196d', '#f2b8a2', 'fdbb2f', '27d193']; let button = document.getElementById('button'); button.addEventListener('click', function changeColor() { let randomColor = colors[Math.floor(Math.random() * colors.length)]; document.body.style.backgroundColor = `${randomColor}`; });
<body> <div class="box"> <div> <p>Hex color code: #ffffff</p> <button id="button">Change Color</button> </div> </div> </body>
这是正确的代码
const colors = ['#e5051b','#f6e06a', '#f1a432', '#a9b724', '#458a92', '#aa0c90', '#301196d', '#f2b8a2', 'fdbb2f', '27d193'];
let button = document.getElementsByClassName('button');
console.log(button);
button[0].addEventListener('click',function changeColor()
{
const color = colors[Math.floor(Math.random()*colors.length)];
console.log(color)
document.body.style.backgroundColor = `${color}`;
});
首先,如评论中所述,您使用了错误的元素选择器。
let button = document.querySelector('.button');
之后,您应该将随机化代码放入点击事件侦听器中,以便每次点击按钮时都会生成随机颜色
button.addEventListener('click',function changeColor()
{
let random_color = colors[Math.floor(Math.random()*colors.length)];
document.body.style.backgroundColor = `${color}`;
});
你在这里做错了两件事。 第一个是,通过 id 获取DOM
中不存在的元素。 因此,您必须在控制台中收到错误消息。 其次,您只是在脚本运行时选择随机颜色,而不是每次单击按钮时。
因此,您应该做的是,将class="button"
更改为id="button"
或将getElementById
更改为getElementsByClassName[0]
。 要在每次点击时获得随机颜色,您应该移动点击处理程序内的逻辑以每次运行它并从给定的颜色数组中选择一个随机颜色。
const colors = ['#e5051b', '#f6e06a', '#f1a432', '#a9b724', '#458a92', '#aa0c90', '#301196d', '#f2b8a2', 'fdbb2f', '27d193']; const randomColor = colors[Math.floor(Math.random() * colors.length)]; let button = document.getElementById('button'); let p = document.getElementById('color'); button.addEventListener('click', function changeColor() { const randomColor = colors[Math.floor(Math.random() * colors.length)]; const color = randomColor; document.body.style.backgroundColor = `${color}`; p.textContent = `Hex color is ${color}` });
<body> <div class="box"> <div> <p id="color">Hex color is #ffff</p> <button id="button">Change Color</button> </div> </div> </body>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.