DIV CSS 佈局教程網

JavaScript 隨機生成 DIV 背景色的兩種做法
編輯:關於JavaScript     

想讓頁面上的色塊隨機變色?CSS 顏色有兩種常見表示法:rgb(xxx,xxx,xxx) 與 #xxxxxx。下面分別實作,並說明各自的取值邏輯。

效果預覽:https://wjf444128852.github.io/DEMOLIST/JS/test/index.html

思路拆解

rgb 寫法:三個 xxx 都是 0 到 255 之間的隨機整數。用 Math.random() * 255 取得隨機小數,再用 Math.floor() 取整數部分。

十六進位寫法:六個字元都是 0–9 與 A–F 的隨機組合。把 16 個可用字元放進陣列,取 6 次,每次隨機挑一個索引(0–15)。

一個容易誤會的點:用 #xxxxxx 賦值後,瀏覽器在 DOM 中讀取 background-color 時,實際拿到的仍是 rgb() 格式的字串。這只是瀏覽器內部正規化的結果,不影響你在程式碼中指定 #xxx。

HTML 結構

<body>
<div class="main">
  <p><a href="javascript:;" id="btn-one">RandomColor-rgb</a></p>
  <ul>
    <li><div class="bg_color"></div></li>
    <li><div class="bg_color"></div></li>
    <li><div class="bg_color"></div></li>
    <li><div class="bg_color"></div></li>
  </ul>
</div>
<div class="main">
  <p><a href="javascript:;" id="btn-two">RandomColor-#XXXXXX</a></p>
  <ul>
    <li><div class="bg_two"></div></li>
    <li><div class="bg_two"></div></li>
    <li><div class="bg_two"></div></li>
    <li><div class="bg_two"></div></li>
  </ul>
</div>
</body>

CSS

*{ box-sizing: border-box; list-style: none; border: none; padding: 0; margin: 0; }
p{ text-align: center; margin: 20px; }
p a{ font-size: 20px; font-weight: 300; color: #e4393c; text-decoration: none;
      padding: 6px 10px; border: 1px solid currentColor; }
.bg_color,.bg_two{ width: 100px; height: 100px; border: 1px solid #aa00aa; }
.main,.main ul{ overflow: hidden; }
.main{ width: 400px; margin: 30px auto; }
.main ul li{ float: left; }

JavaScript

<script>
(function(){
  // 做法一:rgb 隨機色
  function getRandomColor(){
    var rgb = 'rgb(' + Math.floor(Math.random() * 255) + ','
                  + Math.floor(Math.random() * 255) + ','
                  + Math.floor(Math.random() * 255) + ')';
    console.log(rgb);
    return rgb;
  }

  var btn_one = document.querySelector("#btn-one");
  var Divs = document.querySelectorAll(".bg_color");
  btn_one.onclick = function(){
    for (var i = 0; i < Divs.length; i++){
      Divs[i].style.backgroundColor = getRandomColor();
    }
  };

  // 做法二:#XXXXXX 隨機色
  var btn_two = document.querySelector("#btn-two");
  var divsTwo = document.querySelectorAll(".bg_two");
  var chars = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'];

  function generateMixed(n){
    var res = "#";
    for (var i = 0; i < n; i++){
      var id = Math.floor(Math.random() * 16);
      res += chars[id];
    }
    return res;
  }

  btn_two.onclick = function(){
    for (var i = 0; i < divsTwo.length; i++){
      divsTwo[i].style.backgroundColor = generateMixed(6);
    }
  };
})()
</script>

兩個做法的核心都是 Math.random(),差別只在於最後要不要把隨機數映射到十六進位字元表。理解了這個對應關係,改寫成 HSL 或其他色彩模型也只是換個組字規則而已。

以上就是本文的全部內容,希望對你的學習有所幫助。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved