js-实现选项卡功能

<style>
        * {
            margin: 0;
            padding: 0;
        }
        
        ul,
        li {
            list-style: none;
        }
        
        #tab_control {
            width: 300px;
            border: 1px solid #ccc;
            margin: 200px auto;
        }
        
        #tab_list {
            height: 60px;
        }
        
        #tab_list li {
            float: left;
            width: 100px;
            height: 60px;
            background-color: rgba(0, 0, 0, 0.2);
            text-align: center;
            line-height: 60px;
        }
        
        #tab_control>div {
            width: 300px;
            height: 350px;
        }
        
        #img_tab {
            background-color: pink;
            display: none;
        }
        
        #special_tab {
            background-color: powderblue;
            display: none;
        }
        
        #hot_tab {
            background-color: floralwhite;
            display: none;
        }
        /* 给选中的列表项和内容设置样式 */
        
        #tab_list .active {
            background-color: rgba(0, 0, 0, 0.3);
        }
        
        #tab_control .on {
            display: block;
        }
    </style>
</head>

<body>
    <!-- 选项卡 -->
    <div id="tab_control">
        <ul id="tab_list">
            <li id="tab01" class="active">图片</li>
            <li id="tab02">专栏</li>
            <li id="tab03">热点</li>
        </ul>
        <div id="img_tab" class="on">
            图片内容
        </div>
        <div id="special_tab">
            专栏内容
        </div>
        <div id="hot_tab">
            热点内容
        </div>
    </div>
    <script>
        window.onload = function() {
            // 获取选项卡列表
            let lis = document.querySelectorAll('#tab_list li')
                // 获取选项卡内容
            let tab_content = document.querySelectorAll('#tab_control>div')
            console.log(tab_content)
                // 遍历选项卡列表和选项卡内容
            for (let i = 0; i < lis.length; i++) {
                // 给选项卡列表绑定光标滑过事件
                lis[i].addEventListener('mouseover', function() {
                    //遍历选项卡内容
                    for (let j = 0; j < tab_content.length; j++) {
                        // 清除lis和tab_content的className属性
                        lis[j].className = ''
                        tab_content[j].className = ''
                    }
                    // 让lis和tab_conten的索引保持一致,
                    lis[i].className = 'active'
                    tab_content[i].className = 'on'
                })

            }
        }
    </script>
</body>

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值