[HTML]初学者js最简单的随机改变背景颜色

利用改变rgb颜色的随机数(Math.random())给背景颜色赋值

从而实现对背景颜色的随机改变

<script>
function randomNumber(){
            a=Math.floor(Math.random()*10)
            b=Math.floor(Math.random()*10)
            c=Math.floor(Math.random()*10)
            d=Math.floor(Math.random()*10)
            e=Math.floor(Math.random()*10)
            f=Math.floor(Math.random()*10)
            backgroundColor="#"+a+b+c+d+e+f
            return backgroundColor
        }
</script>

return        返回值

Math.random()随机数只能取0-1之间的所有随机数

例如:

<script>
    a=Math.random()
    console.log(a)
</script>

输出结果为:

        

 

 Math.floor()向下取整

当两个函数结合起来用就能实现随机取0-9之间的所有随机整数:

Math.floor(Math.random()*10)

随机数乘以10再向下取整就能得到较为均衡的0-9之间的随机整数

在写一个方法样式改变背景颜色

<script>
    function backGroundColor(){
            document.body.style.backgroundColor=randomNumber()
        }
</script>

最后设置一个按钮调用方法backGroundColor()

注意驼峰命名法

<button type="button" onclick="backGroundColor()">点我切换背景颜色</button>

接下来看源码和效果:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <button type="button" onclick="backGroundColor()">点我切换背景颜色</button>
    <script>
        function randomNumber(){
            a=Math.floor(Math.random()*10)
            b=Math.floor(Math.random()*10)
            c=Math.floor(Math.random()*10)
            d=Math.floor(Math.random()*10)
            e=Math.floor(Math.random()*10)
            f=Math.floor(Math.random()*10)
            backgroundColor="#"+a+b+c+d+e+f
            return backgroundColor
        }
        function backGroundColor(){
            document.body.style.backgroundColor=randomNumber()
        }
    </script>  
</body>
</html>

效果如下:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序猿_小以

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值