zishu's blog

zishu's blog

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

Generate random background colors using JavaScript.

Start by creating 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 then convert it to hexadecimal format. The following code generates a random 6-digit number and performs the conversion:

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

You can check the result by outputting it to the console. It will generate a random result like #62113b.

Next, you need to assign this color to the above <li> tags. First, you need to iterate through all the <li> tags and create an array. You can use a for loop for this:

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

Then, loop through the array and apply the random color to each <li> tag. Again, you can use a for loop for this:

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 will run after the page has finished loading, so you need to use window.onload to add the event and combine all the code together.

Check the result:

To see the effect, copy all of this 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'), 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 a better approach, feel free to comment!

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