<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style type="text/css"> #main{ height: 400px; width: 400px; margin: 20px auto; } ...
<!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="胡歌" />
<div style="display: block;">楊洋好帥</div>
<div>林志穎有可愛的kimi</div>
<div>宋仲基歐巴</div>
<div>胡歌是個大帥哥</div>
</div>
</body>
<script type="text/javascript">
//選項卡的原理,先讓所有的都隱藏,然後讓當前的顯示
var main=document.getElementById("main");
var but=main.getElementsByTagName("input");
var div=main.getElementsByTagName("div");
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>