1. 程式人生 > 其它 >選項卡功能隨筆

選項卡功能隨筆

<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一一對應

還有一個問題就是涉及到排他思想,自身有樣式然後其他沒有樣式,所以點選按鈕給高亮之前要將所有按鈕高亮清除,這裡就是通過再遍歷一遍元素組清除樣式