zishu's blog

zishu's blog

一个热爱生活的博主。https://zishu.me

Generate random background colors using JavaScript.

First, create a simple HTML page:

<style>
  /* ... */
</style>

<ul>
  <li>html</li>
  <li>css</li>
  <li>js</li>
</ul>

You can use the Math.random() property to generate a random number and convert it to hexadecimal format. The following code generates a random 6-digit number and converts it:

const randomHex = () => `#${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0")}`;

You can check the result by outputting it to the console. It generates a random result of #62113b.

Next, you need to assign this color to the li tags. First, create an array by iterating through all the li tags using a for loop:

var arr = document.getElementsByTagName('li');
var temp = [];
for (var i = 0; i < arr.length; i++) {
  temp.push(arr[i].innerHTML);
}

Then, loop through the array and assign a random color to each li tag using another for loop:

var li = document.getElementsByTagName("li");
for (var i = 0; i < li.length; i++) {
  
  for (var num = 0; num < li.length; num++) {
    li[num].style.background = randomHex();
  }

}

These events should run after the page has finished loading, so you need to use the window.onload event and combine all the code together.

To see the effect, copy the code and run it locally:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Randomly Generated Colors</title>
  <style>
    body {
      display: flex;
      justify-content: center;
      padding-top: 100px;
    }
    ul {
      list-style: none;
      padding: 0;
      display: flex;
    }
    li {
      width: 100px;
      height: 40px;
      color: #333;
      display: flex;
      justify-content: center;
      align-items: center;
      margin-right: 30px;
    }
  </style>
</head>
<body>
  <ul>
    <li>html</li>
    <li>css</li>
    <li>js</li>
  </ul>
  <script>
    const randomHex = () => `#${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0")}`;
    console.log(randomHex());

    var arr = document.getElementsByTagName('li');
    var temp = [];
    for (var i = 0; i < arr.length; i++) {
      temp.push(arr[i].innerHTML);
    }

    window.onload = function () {
      var li = document.getElementsByTagName("li");
      for (var i = 0; i < li.length; i++) {
        
        for (var num = 0; num < li.length; num++) {
          li[num].style.background = randomHex();
        }

      }
    }
  </script>
</body>
</html>

If you have any better suggestions, please leave a comment!

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.