JavaScript实现tab选项卡效果

标签: JavaScript  js

css代码

<style>
        *{
            margin: 0;
            padding: 0;
        }
        .container{
            width: 500px;
            /*height: 700px;*/
            border: 1px solid #000;
            margin: 100px auto;

        }
        .container>ul{
            background-color: skyblue;
            list-style: none;
            display: flex;
            justify-content: space-between;
            width: 100%;
            height: 60px;
            line-height: 60px;
        }
        ul>li{
            width: 100px;
            font-size: 20px;
            border-right: 1px solid #000000;
            text-align: center;
            cursor: default;
        }
        ul>li:last-child{
            border-right: none;
        }

        .content{
            width: 100%;
            height: 300px;
        }

        .bottom>.content:nth-child(1){
            background-color: pink;
        }
        .bottom>.content:nth-child(2){
            background-color: purple;
            display: none;
        }
        .bottom>.content:nth-child(3){
            background-color: greenyellow;
            display: none;
        }
        .bottom>.content:nth-child(4){
            background-color: orange;
            display: none;
        }
        .bottom>.content:nth-child(5){
            background-color: darkcyan;
            display: none;
        }

        .current{
            background-color: brown;
        }
    </style>

html代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>tab选项卡</title>
    
</head>
<body>
    <div class="container">
        <ul>
            <li class="current">新闻</li>
            <li>科技</li>
            <li>数码</li>
            <li>游戏</li>
            <li>搞笑</li>
        </ul>

        <div class="bottom">
            <div class="content">新闻内容</div>
            <div class="content">科技内容</div>
            <div class="content">数码内容</div>
            <div class="content">游戏内容</div>
            <div class="content">搞笑内容</div>
        </div>

    </div>
    
</body>
</html>

JavaScript代码

<script>
        // 拿到所有的选项卡
        let items = document.querySelectorAll("li");

        // 拿到所有的内容
        let contents = document.querySelectorAll(".content");

        // 上一次选中的选项卡的索引
        let preIndex = 0;

        //  为所有选项卡添加单机响应事件
        for (let i = 0; i < items.length; i++) {
           items[i].onclick = function () {
              items[preIndex].className = "";
              contents[preIndex].style.display = "none";
              items[i].className = "current";
              contents[i].style.display = "block";
              preIndex = i;
           };
        }
    </script>

运行效果

版权声明:本文为weixin_44120487原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_44120487/article/details/105870045