基于JavaScript實現(xiàn)選項卡效果
一個簡單的選項卡的關鍵在于:當切換頁面時,如何讓所選的選項和與其對應的內容同時出現(xiàn),并且在選擇其他的內容時,不影響新的內容的顯示。
其中用到兩個很關鍵的思想:
1.為對象增加index屬性,并通過this對index 的調用來使每個選項能顯示出所對應的內容,并且屬性值要設置為循環(huán)時的數值-i。
2.通過對class(類)的靈活使用,來改變當先所選中目標的樣式。
3、用for循環(huán)嵌套事件對每一項進行遍歷。
4、在編譯時,位于body中的div和input要有預先定義的行內樣式或者信息。
5、button和div.style.display要同時清零,同時出現(xiàn)才能達到選項卡的目的。
代碼:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>選項卡</title> <style type="text/css"> #div1 .active{ background: red; color: white; } #div1 div{ width: 237px; height:150px; background:#CCC; display: none; } </style> <script type="text/javascript"> window.onload=function(){ var oDiv = document.getElementById('div1'); var btn = oDiv.getElementsByTagName('input'); var aDiv = oDiv.getElementsByTagName('div'); for (var i = 0; i < btn.length; i++) { btn[i].index=i; //給btn增加一個index的屬性 btn[i].onmouseover = function(){ for (var i = 0; i < btn.length; i++) { btn[i].className = ''; aDiv[i].style.display = 'none'; } this.className = 'active'; aDiv[this.index].style.display = 'block'; //調用index屬性 } } }; </script> </head> <body> <div id="div1"> <input type="button" value="首頁" class="active"> <input type="button" value="菜單"> <input type="button" value="幫助"> <input type="button" value="聯(lián)系"> <input type="button" value="贊助"> <div style="display: block;">這是首頁</div> <div>這是菜單</div> <div>這是幫助</div> <div>這是聯(lián)系</div> <div>這是贊助</div> </div> </body> </html>
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
微信小程序MUI側滑導航菜單示例(Popup彈出式,左側滑動,右側不動)
這篇文章主要介紹了微信小程序MUI側滑導航菜單,結合實例形式分析了微信小程序Popup彈出式,左側滑動,右側不動菜單功能相關實現(xiàn)技巧與注意事項,需要的朋友可以參考下2019-01-01