标签搜索
jQuery 实现TAB选项卡事件
jQuery 实现TAB选项卡事件
3年前 1.07k 阅读
  • 首页
  • /
  • 笔记
  • /
  • 正文
  • 原理

    1. 点击上部的 li,当前 li 添加 current 类,其余兄弟移除类
    2. 点击的同时,得到当前 li 的索引号
    3. 让下部里面相应索引号的 item 显示,其余的 item 隐藏

    实现

    <!DOCTYPE html>
    <html lang="en">
    
    <head>
        <meta charset="UTF-8">
        <title>tab-jQuery</title>
        <style>
            * {
                margin: 0;
                padding: 0;
                list-style: none;
            }
    
            .container {
                width: 600px;
                margin: 100px auto 0;
                overflow: hidden;
            }
    
            .tab_list {
                height: 30px;
                width: 600px;
            }
    
            .tab_list li {
                float: left;
                height: 30px;
                line-height: 30px;
                width: 200px;
                font-size: 20px;
                text-align: center;
                color: #ccc;
                background: green;
                cursor: pointer;
            }
    
            .tab_con li {
                display: none;
                height: 200px;
                width: 600px;
                background: pink;
                font-size: 100px;
                line-height: 200px;
                text-align: center;
            }
    
            .tab_list .current {
                background: red;
                color: #ccc;
            }
    
            .tab_con .item {
                display: block;
            }
        </style>
    </head>
    
    <body>
        <div class="container">
            <ul class="tab_list">
                <li class="current">标题1</li>
                <li>标题2</li>
                <li>标题3</li>
            </ul>
            <ul class="tab_con">
                <li class="item">内容111</li>
                <li>内容222</li>
                <li>内容333</li>
            </ul>
        </div>
    </body>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $('.tab_list li').click(function () {
            var index = $(this).index();
            $(this).addClass('current').siblings().removeClass('current');
            $('.tab_con li').eq(index).show().siblings().hide();
        });
    </script>
    
    </html>

    效果

    tab.gif

    1
    那年今日

    评语 (0)

    取消