随机颜色的多种写法

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

  方法一

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

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="width: 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="width: 100px;height: 100px">
 
 

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

 

 

转载于:https://www.cnblogs.com/yhyanjin/p/7152685.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值