zoukankan      html  css  js  c++  java
  • javascript随机变色--案例

    1.打开网页,网页效果如图所示

    代码如下: 

     1 <!DOCTYPE html>
     2 <html>
     3 <head>
     4     <meta charset="utf-8">
     5     <title>随机变色</title>
     6     <style type="text/css">
     7         #box{
     8             width: 200px;
     9             height: 200px;
    10             border: 1px solid red;
    11         }
    12     </style>
    13 </head>
    14 <body>
    15 
    16 <div id="box"></div>
    17 <script type="text/javascript">
    18     // 获取元素对象
    19     var obj1 = document.getElementById("box");
    20     // 给元素添加属性
    21     obj1.style.background = 'rgb(255,255,0)'; // 注意:添加的属性类型 是字符串类型 !!!
    22 </script>
    23 </body>
    24 </html>

    2.思考:如何随机变换div块的背景颜色

    • 添加随机函数
    • 颜色的表示方式  rgb(随机数,随机数,随机数)
    • 添加多次定时器
     1 <body>
     2 
     3 <div id="box"></div>
     4 <script type="text/javascript">
     5     // 获取元素对象
     6     var obj1 = document.getElementById("box");
     7     // 给元素添加属性
     8     // obj1.style.background = 'rgb(255,255,0)';
     9 
    10     // 多次定时器
    11     setInterval(function(){
    12         obj1.style.background = "rgb("+rand(0,255)+","+rand(0,255)+","+rand(0,255)+")";
    13     },200);
    14 
    15     // 随机函数
    16     function rand(n,m){
    17         return Math.floor(Math.random()*(m-n+1));
    18     }
    19 </script>
    20 </body>
  • 相关阅读:
    腾讯云 Serverless 产品动态 20200827
    双指针 86. 分隔链表(链表 dummyhead)
    双指针:15. 三数之和
    双指针:283. 移动零
    双指针:167. 两数之和 II
    关于数组
    关于抽象类,接口以及多态
    关于字符串
    关于异常
    动手动脑3
  • 原文地址:https://www.cnblogs.com/pjcd-32718195/p/11674773.html
Copyright © 2011-2022 走看看