每次单击按钮时随机选择颜色

Random color each time button is clicked

本文关键字:随机 选择 颜色 按钮 单击      更新时间:2023-10-31

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

var makeColor ="#" + Math.floor((Math.random() * 999) + 1);
$("button").click(function(){
  $("div").css("background",makeColor);
});

为此任务使用函数

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>