JS实现tab栏的切换

来源:互联网 发布:淘宝买药暗语 编辑:程序博客网 时间:2024/05/18 03:00
<!DOCTYPE html><html><head lang="en">    <meta charset="UTF-8">    <title></title>    <style>        *{margin: 0px;padding: 0px;}        #box{            margin: 50px auto;            width:400px;        }        .top{            width: 400px;        }        .bottom div{            width: 400px;            height: 400px;            background-color: aquamarine;            display: none;        }        .current{            background-color: gold;        }        .bottom .show{            display: block;        }    </style>    <script>        window.onload = function () {            function tabs(id) {                var box = document.getElementById(id);                var btns = box.getElementsByTagName('button');                var divs = document.getElementById('divs').children;                for (var i=0; i<btns.length; i++){                    // 保存索引                    btns[i].index = i;                    // 排他思想 每次点击都先去掉所有选项的class,然后只给点击的选项添加class。                    btns[i].onclick = function () {                        for(var j=0;j<btns.length; j++){                            btns[j].className = "";                            divs[j].className = '';                        }                        this.className = 'current';                        divs[this.index].className = 'show';                    }                }            }            tabs("box");        }    </script></head><body><div id="box">    <div class="top">        <button>第一个盒子</button>        <button>第二个盒子</button>        <button>第三个盒子</button>        <button>第四个盒子</button>    </div>    <div class="bottom" id="divs">        <div class="show">1盒子</div>        <div>2盒子</div>        <div>3盒子</div>        <div>4盒子</div>    </div></div></body></html>
0 0
原创粉丝点击