随机颜色的多种写法

  今天给大家讲讲随机颜色怎么来实现。以下是我的两种方法;

  方法一

    十六进制随机颜色:字符串的拼接;

js:

function ranColor(){
    var colors="#";
    for(var i=0; i<6;i++){
        colors=colors+Math.floor(Math.random()*16).toString(16);
    }
    return colors;
}
        var oDiv=document.getElementById('div');
        oDiv.style.background=ranColor();


html:

<div id="div" style=" 100px;height: 100px"></div>

   方法二:

    使用RGB来实现随机颜色:

       1.写一个随机数范围0-255
     2封装一个函数, 返回字符串拼接 【rgb (1,1,1)
js:

function getRan(a,b){
    return  Math.floor(Math.random()*(b-a+1)+a)
}

function rgeColor(){
    return "rgb("+getRan(0,255)+","+getRan(0,255)+","+getRan(0,255)+")"
}
//alert(rgeColor())

var oDiv=document.getElementById('div')
oDiv.style.background=rgeColor();


html:

<div id="div" style=" 100px;height: 100px">

注意:JS必须全部写在window.onload中 。

 
原文地址:https://www.cnblogs.com/yhyanjin/p/7152685.html