JS实现简单的选项卡效果

原生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>

效果图
JS实现简单的选项卡效果_第1张图片
。。。。。。。。嗝~~

你可能感兴趣的:(JavaScript)