標籤:index border nice element meta width doc css name
<!DOCTYPE html><html><head> <meta charset="UTF-8"> <title>簡單的選項卡</title> <style type="text/css"> #main{ height: 400px; width: 400px; margin: 20px auto; } #main>div{ height: 300px; width: 300px; background-color: lightpink; color: white; font-size: 30px; text-align: center; line-height: 300px; display: none; } #main>div:nth-child(2){ background-color:yellow; } #main>div:nth-child(3){ background-color:greenyellow; } #main>div:nth-child(4){ background-color: #1E90FF; } input{ margin: 13px; border-radius: 5px; background-color: coral; border: 1px solid dodgerblue; } .color{ background-color: red; } </style></head><body><div id="main"> <input type="button" id="but1" value="周杰倫" class="color"/> <input type="button" id="but2" value="五月天" /> <input type="button" id="but3" value="盧廣仲" /> <input type="button" id="but4" value="Eminem" /> <div style="display: block;">周杰倫的歌我全部都會唱!!</div> <div>五月天的歌曲很好聽</div> <div>盧廣仲的閩南歌很nice</div> <div>Eminem的歌很COOL</div></div></body><script type="text/javascript"> //選項卡的原理,先讓所有的都隱藏,然後讓當前的顯示 var main=document.getElementById("main"); var but=main.getElementsByTagName("input"); var div=main.getElementsByTagName("div"); //display:none 表示的是隱藏 for (var i=0;i<but.length;i++) { but[i].index=i;//給每個按鈕增加一個index,把index改成其他的也可以 but[i].onclick=function(){//綁定點擊事件 for (var i=0;i<but.length;i++) { div[i].style.display="none";//讓所有div隱藏 but[i].className=" ";//用迴圈清除所有but的className } this.className="color";//給當前的but加上className,使其在點擊時變色 div[this.index].style.display="block";//讓當前對應的div顯示 } }</script></html>
js製作一個簡單的選項卡