样式部分: 
<style>
        *{
            margin: 0;
            padding: 0;
        }
        a{
            text-decoration: none;
            color: #666;
        }
        ul li{
            display: inline-block;
            height: 20px;
            width: 60px;

 

        }
        ul li a{
            display: block;
            text-align: center;
            background-color: cornflowerblue;
        }
        .active{
            background-color: darkcyan;
        }
        .content{
            width: 186px;
            height: 200px;
            border: 1px solid #ccc;
        }
    </style>
    <script>
        window.onload=function(){
            var as=document.querySelectorAll("li a");
            var cons=document.querySelectorAll(".content");
使用for循环
            for (var i = 0; i < as.length; i++) {
               as[i].onclick=function(){
                  for (var j = 0; j < as.length; j++) {
                     as[j].className="";
                  }
                  this.className="active";
                  var idx=this.attributes["data-idx"].value;
                  for (var j = 0; j < cons.length; j++) {
                      cons[j].style.display="none";
                     
                  }
                  cons[idx].style.display="block";
               }
               
            }
        }
    </script>
</head>
HTML部分
<body>
    <ul>
        <li><a href="#" class="active" data-idx="0">列表1</a></li>
        <li><a href="#" data-idx="1">列表2</a></li>
        <li><a href="#" data-idx="2">列表3</a></li>
    </ul>
    <div class="content"></div>
</body>
</html>
页面部分:



posted on 2021-11-07 20:52  于凡芮  阅读(74)  评论(0)    收藏  举报