选项卡功能随笔

<body>
    <div id="box">
       <button class="color">one</button><button>two</button><button>three</button>
        <div class="one">第一块</div>
        <div class="one">第二块</div>
        <div class="one">第三块</div>
    </div>
    <script>
        var box = document.getElementById("box");
        console.log(box);
        var btn = document.getElementsByTagName("button");
        var div = document.getElementsByClassName("one");
        console.log(div);
        console.log(btn);
        for(var i=0;i<btn.length;i++){
            btn[i].index = i;//给btn设置下标值,方便后面跟下面div一一对应
            btn[i].onclick = function (){
                for(var n=0;n<div.length;n++){
                    btn[n].className = "";
                    div[n].style.display = "none";//做一个排他处理,将所有元素样式清除
                }
                this.className = "color";
                div[this.index].style.display = "block";//给点击的元素添加样式
            }
            if(i!=0){
                div[i].style.display = "none";//刚开始的时候给除默认元素外的其他元素隐藏样式
            }
        }
    </script>
</body>

  实现思想就是点击一个按钮显示一个模块同时点击的按钮高亮显示,主要的问题就是按钮跟模块如何一一对应,于是就有了给按钮组设置下标index,div就可以根据这个下标与btn一一对应

还有一个问题就是涉及到排他思想,自身有样式然后其他没有样式,所以点击按钮给高亮之前要将所有按钮高亮清除,这里就是通过再遍历一遍元素组清除样式

posted @ 2022-03-02 18:41  binlong  阅读(46)  评论(0)    收藏  举报