js implements li selection to add styles and delete other li selection styles

The id needs to be set in the outer DOM.

Select the current li to change the color, and delete the selected style of other li. Click the selected li again to remove the selected style.

<!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>Document</title>
  <style>
    *{
    
    
      margin:0;
      padding:0;
    }
    .active{
    
    
      color:brown;
    }
  </style>
</head>
<body>
  <div>
    <ul id="menu">
      <li class="active" onclick="setStyle(event)">首页</li>
      <li onclick="setStyle(event)">产品</li>
      <li onclick="setStyle(event)">新闻</li>
    </ul>
  </div>
  <script>
    function setStyle(event) {
    
    
      let el=document.getElementById("menu");
      let current=el.querySelector(".active");
      if (event.target.className==="active") {
    
    
        event.target.className="";
      } else {
    
    
        if(current) current.className="";
        event.target.className="active";
      }

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

Guess you like

Origin blog.csdn.net/qq_34661750/article/details/113850373