如何使用javascript更改背景颜色?

如何使用javascript更改背景颜色?,javascript,html,Javascript,Html,我想将背景颜色更改为从数组中随机选择的颜色,但我不确定我在做什么。我最困惑的是如何使按钮工作 这是HTML的主体,最终我必须将文本更改为它更改为的颜色的名称,但我想先获得颜色: 常量颜色=['e5051b','f6e06a','f1a432','a9b724','458a92','aa0c90','301196d','f2b8a2','fdbb2f','27d193']; const randomColor=colors[Math.floorMath.random*colors.length]

我想将背景颜色更改为从数组中随机选择的颜色,但我不确定我在做什么。我最困惑的是如何使按钮工作

这是HTML的主体,最终我必须将文本更改为它更改为的颜色的名称,但我想先获得颜色:

常量颜色=['e5051b','f6e06a','f1a432','a9b724','458a92','aa0c90','301196d','f2b8a2','fdbb2f','27d193']; const randomColor=colors[Math.floorMath.random*colors.length]; let button=document.getElementById'button'; 按钮。addEventListener“单击”,函数更改颜色{ 常量颜色=随机颜色; document.body.style.backgroundColor=`${color}`; }; 十六进制颜色代码:ffffff

变色
每次单击都必须随机添加颜色

常量颜色=['e5051b','f6e06a','f1a432','a9b724','458a92','aa0c90','301196d','f2b8a2','fdbb2f','27d193']; let button=document.getElementById'button'; 按钮。addEventListener“单击”,函数更改颜色{ 让randomColor=colors[Math.floorMath.random*colors.length]; document.body.style.backgroundColor=`${randomColor}`; }; 十六进制颜色代码:ffffff

变色 您正试图通过id获取按钮的引用,您在按钮中使用了类 GetElementsByCassName返回需要选择第一个数组的数组 颜色将只生成一次并以颜色存储。如果您想在每次需要生成随机颜色时单击 这是正确的代码

常量颜色=['e5051b'、'f6e06a'、'f1a432'、'a9b724'、'458a92'、'aa0c90'、'301196d'、'f2b8a2'、'fdbb2f'、'27d193']; let button=document.getElementsByClassName'button'; console.logbutton; 按钮[0]。添加EventListener“单击”,函数更改颜色 { const color=colors[Math.floorMath.random*colors.length]; 控制台。logcolor document.body.style.backgroundColor=`${color}`; };
首先,正如注释中提到的,您使用了错误的元素选择器

 let button = document.querySelector('.button');
之后,您应该将随机化代码放入click事件侦听器中,以便在每次单击按钮时生成随机颜色

button.addEventListener('click',function changeColor() 
{
   let random_color = colors[Math.floor(Math.random()*colors.length)];
   document.body.style.backgroundColor = `${color}`;
});

这里有两件事你做错了。 第一个是,通过DOM中不存在的id获取元素。因此,您必须在控制台中获得一个错误。 其次,您只是在脚本运行时选择一种随机颜色,而不是每次单击按钮时

因此,您应该做的是,将class=button更改为id=button,或者将getElementById更改为getElementsByClassName[0]。 要在每次单击时获得随机颜色,您应该在单击处理程序中移动逻辑,以便每次运行它,并从给定的颜色数组中选择随机颜色

常量颜色=['e5051b','f6e06a','f1a432','a9b724','458a92','aa0c90','301196d','f2b8a2','fdbb2f','27d193']; const randomColor=colors[Math.floorMath.random*colors.length]; let button=document.getElementById'button'; 设p=document.getElementById'color'; 按钮。addEventListener“单击”,函数更改颜色{ const randomColor=colors[Math.floorMath.random*colors.length]; 常量颜色=随机颜色; document.body.style.backgroundColor=`${color}`; p、 textContent=`Hex color为${color}` };

十六进制颜色为ffff

变色
首先,将class=button更改为id=button,因为您将在jsp中获取id为的元素引用,然后更改为一个函数:const randomColor==>colors[Math.floorMath.random*colors.length];calli it document.body.style.backgroundColor=randomColoror document.querySelector.button或delegate,以防按钮更多。这更有意义:它们同样兼容,实际上querySelector比getElementsByClassName更兼容一点,这与2020年无关。是的,它们可以互换使用。我个人投票支持querySelector,因为在使用querySelectorAll时很容易区分。您知道选择一种或多种类型的场景