利用改变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>

效果如下:

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐