2016-04-01 107 views
-1

我希望div每次点击按钮时都会变为由我的makeColor变量生成的随机颜色。提前致谢。每次单击随机颜色按钮

var makeColor ="#" + Math.floor((Math.random() * 999) + 1); 

$("button").click(function(){ 
    $("div").css("background",makeColor); 
}); 

回答

2

使用函数完成这个任务

function randomColor() { 
 
    var c = "#"; 
 
    for (var i = 0; i < 6; i++) { 
 
     c += (Math.random() * 16 | 0).toString(16); 
 
    } 
 
    return c; 
 
} 
 

 
var a = document.getElementById("id1").style; 
 
a.color = randomColor();
<h1 id="id1">stackoverflow</h1>