JavaScript实现简单选项卡

标签: JavaScript练习  js  javascript  html  html5

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        ul {
            list-style: none;
        }
        .box{
            width: 398px;
            margin: 100px auto;
        }
        li{
            float: left;
            width: 98px;
            height: 42px;
            border: 1px solid red;
            border-right: 0;
            text-align: center;
            line-height: 42px;
            cursor: pointer;
        }
        .content{
            width: 395px;
            height: 140px;
            border: 1px solid red;
            border-top: 0;
            display: none;
        }
        .active{
            background: #FF4400;
            color: #fff;
        }
        .clearfix::after{
            content: '';
            display: block;
            height: 0;
            clear: both;
        }
    </style>
</head>
<body>
    <div class="box">
        <!-- 清除浮动 -->
        <ul class="clearfix"> 
            <li class="active">手机</li>
            <li>美食</li>
            <li>电脑</li>
            <li style="border-right: 1px solid red;">衣服</li>
        </ul>
        <div class="content" style="display: block;">
            手机
        </div>
        <div class="content">
            美食
        </div>
        <div class="content">
            电脑
        </div>
        <div class="content">
            衣服
        </div>
    </div>
    
</body>
<script>
    var lis = document.querySelectorAll('li');
    var divs = document.querySelectorAll('.content');

    for(var i = 0; i<lis.length;i++){
        lis[i].index = i;
        lis[i].onclick = function(){
        //利用排他思想 先全部移除然后再设置
            for(var j = 0; j<lis.length;j++){
                lis[j].className = ''
                divs[j].style.display="none"
            }
            this.className = 'active'
            divs[this.index].style.display="block"
        }
    }

</script>
</html>

选项卡
选项卡实例图

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