Jquery 实现选项卡

编写代码

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <!-- 导入jquery文件-->
    <script src="jquery\jquery.js"></script>

    <style type="text/css">
        * {
            margin: 0px;
            padding: 0px;
        }
        
        .tabbox {
            margin: 10px;
        }
        
        .tabbox ul {
            list-style: none;
            display: table;
        }
        
        .tabbox ul li {
            float: left;
            width: 100px;
            line-height: 30px;
            padding-left: 8px;
            border: 1px solid #aaccff;
            margin-right: -1px;
            cursor: pointer;
        }
        
        .tabbox ul li.active {
            background-color: #e73839;
            color: white;
            font-weight: bold;
        }
        
        .tabbox .content {
            border: 1px solid #aaccff;
            padding: 10px;
        }
        
        .tabbox .content>div {
            display: none;
        }
        
        .tabbox .content>div.active {
            display: block;
        }
    </style>

</head>

<body>
    <div class="tabbox">

        <ul>

            <li>选项卡一</li>

            <li class="active">选项卡二</li>

            <li>选项卡三</li>

            <li>选项卡四</li>
        </ul>
        <div class="content">

            <div>
                <div>111111111111</div>
            </div>
            <div class="active">
                <div>2222222222</div>
            </div>
            <div>33333333333</div>

            <div>44444444</div>
        </div>
    </div>

    <script>
        $(function() {  
            $(".tabbox li").click(function()   {     //获取点击的元素给其添加样式,讲其兄弟元素的样式移除
                    
                $(this).addClass("active").siblings().removeClass("active");     //获取选中元素的下标
                    
                var index = $(this).index();    
                $(this).parent().siblings().children().eq(index).addClass("active").siblings().removeClass("active");  
            });
        });
    </script>


</body>

</html>

运行结果


posted @ 2021-08-18 13:44  阿向向  阅读(305)  评论(0编辑  收藏  举报