【问题标题】:Random color each time button is clicked [duplicate]每次单击按钮时随机颜色[重复]
【发布时间】:2016-07-21 20:28:20
【问题描述】:

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

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

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

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    为此任务使用函数

    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();
    &lt;h1 id="id1"&gt;stackoverflow&lt;/h1&gt;

    【讨论】:

      猜你喜欢
      • 2014-10-07
      • 2012-12-06
      • 1970-01-01
      • 1970-01-01
      • 2013-06-02
      • 2018-06-14
      • 2019-08-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多