JS实现简单的选项卡效果

标签: JavaScript

原生js简单选项卡的实现,利用自定义属性

HTML代码:

<div id="main">
        <ul>
            <li class="current">1</li>
            <li>2</li>
            <li>3</li>
        </ul>

        <div class="current">1</div>
        <div>2</div>
        <div>3</div>
</div>

CSS代码:

<style>
        * {  margin: 0; padding: 0;  }

        ul, ol {  list-style: none;}

        #main {
            width: 460px;
            margin: 120px auto;
        }

        #main ul li {
            height: 40px;
            width: 80px;
            border: 1px solid #000;
            text-align: center;
            line-height: 40px;
            display: inline-block;
            margin-right: 5px;
            position: relative;
            top: 1px;
            cursor: pointer;
        }

        #main div {
            width: 460px;
            height: 300px;
            border: 1px solid #000;
            text-align: center;
            padding: 20px;
            font-size: 32px;
            display: none;
        }

        #main ul li.current {
            background-color: darkcyan;
            border-bottom-color: darkcyan;
        }

        #main div.current {
            background-color: darkcyan;
            display: block;
        }
    </style>

JS代码:

<script>

        var main = document.getElementById("main");
        var list = main.getElementsByTagName("li");
        var divs = main.getElementsByTagName("div");

        // 绑定事件
        for (var i = 0; i < list.length; i++) {
            list[i].index = i;
            list[i].onclick = addStyle;
        }

        function addStyle(){
            for(var i=0; i<list.length; i++){
                list[i].className = "";
                divs[i].className = "";
            }
            this.className = "current";
            divs[this.index].className = "current";
        }

</script>

效果图
在这里插入图片描述
。。。。。。。。嗝~~

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