First published blog address: imzsh.com/posts/20210…

Start by writing a simple HTML page

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

<ul>
  <li>html</li>
  <li>css</li>
  <li>js</li>
</ul>
Copy the code

The math.random () attribute generates a random number and then converts it to hexadecimal. Here is the code that generates a random 6-digit number and converts it.

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

You can see the result in the console output, which randomly generates a result # 62113B.

The next step is to pass the color to the li tag above, first iterating through all the Li’s and then generating an array, which can be iterated through using a for loop.

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

Copy the code

The array is then looped through, with each LI tag running a random color generation and passing it to itself. Again, it operates through the 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(); }}Copy the code

These events are run after the page has loaded, so you need to write the event through window.onload and then put all the code together.

Let’s see what happens.

Let’s copy this and run it locally and see what it looks like.

<! DOCTYPEhtml>
<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 color</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 = () = > ` #The ${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>
Copy the code

If you have a better way to write, welcome to comment!