纯javascript的随机背景颜色生成器(无jquery)



var color;

function randomColor() {
color =  '#' + Math.random().toString(16).slice(2, 8);  // Random number converted to hexadecimal         with toString(16) and then slice to make it a 6 digit number. like fe2e4d or f4e22e 
};
var change = document.getElementById('color_change');
change.addEventListener('click', function() {
document.getElementById('random_background').style.backgroundColor  = "color" ; 
});
div{
width:300px;
height:300px;
}
<div id="random_background"></div>
<button id="color_change" >Color Change</button>

我认为最后一部分是问题所在,但我找不到如何正确实现它。请帮忙。

正如@Teemu在注释中所说,您正在为backgroundColor属性设置一个字符串,而不是设置color变量的实际值。

下面是一个在不使用var color;的情况下对您有所帮助的示例使您的randomColor()函数直接返回值。然后在backgroundColor属性中调用该函数,如下所示:

function randomColor() {
return '#' + Math.random().toString(16).slice(2, 8); 
};
var change = document.getElementById('color_change');
change.addEventListener('click', function() {
document.getElementById('random_background').style.backgroundColor = randomColor(); 
});
div{
width: 300px;
height: 150px;
}
<div id="random_background"></div>
<button id="color_change" >Color Change</button>

如果要使用var color,请在设置backgroundColor属性之前调用randomColor(),然后将其设置为变量,而不是字符串:

...
randomColor();
document.getElementById('random_background').style.backgroundColor = color;

"div"为空时没有高度您应该将高度初始化为您的div.

也使用正确的颜色变量。

祝好运

这里为每个三元组使用随机数的解决方案:

function rT(){
//random number between 0 and 255
//you could change the limits or pass a parameter to this function
return Math.floor(Math.random() * (255 - 0)) + 0;
}
var change = document.getElementById('color_change');
change.addEventListener('click', function() {
document.getElementById('random_background').style.backgroundColor = "rgb("+rT()+" "+rT()+" "+rT()+")"; });
//in this case we use this form rgb(0-255,0-255,0-255)

完整示例如下:https://jsfiddle.net/ztavxrse/

更改限制https://jsfiddle.net/c5j6fpnL/

最新更新