具有纯JavaScript的随机背景颜色生成器(无jquery)

时间:2018-07-27 18:21:07

标签: javascript

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>

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

3 个答案:

答案 0 :(得分:1)

如@Teemu在评论中所述,您正在将字符串设置为display属性,而不是设置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属性之前调用randomColor(),然后将其设置为变量,而不是字符串:

backgroundColor

答案 1 :(得分:0)

“ div”为空时没有高度 您应该将高度初始化为div。

还使用正确的颜色变量。

祝你好运

答案 2 :(得分:0)

以下是对每个三元组使用随机数的解决方案:

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/