JavaScript选项卡切换实例
需求
实现简单的选项卡切换功能
代码
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>实践题 - 选项卡</title>
<style type="text/css">
*{
margin:0;padding:0;font-size:13px;
}
li{
list-style-type:none;
}
.field{
height:500px;
width:500px;
}
.field li{
float:left;
display:inline-block;
width:80px;
text-align:center;
height:35px;
line-height:35px;
border:1px solid #ccc;
margin:4px;
cursor:pointer;
}
.field li.actived{
border-top:3px solid #8a4312;
border-bottom:3px solid #fff;
}
.field ul{
height:42px;
border-bottom:3px solid #8a4312;
}
.field div{
width:500px;
height:160px;
border:1px solid grey;
border-top:none;
}
.field p{
margin:5px;
}
.hide{
display:none;
}
.show{
display:block;
}
</style>
<script type="text/javascript">
window.onload = function() {
var tabs = document.getElementById("tab");
var aLi = tabs.getElementsByTagName("li");
var oDiv = document.getElementById("lists");
var aDiv = oDiv.getElementsByTagName("div");
for(var i = 0; i < aLi.length; i++) {
aLi[i].index = i;
aLi[i].onclick = function() {
for(var i = 0; i < aLi.length; i++) {
aLi[i].className = "";
}
this.className = "actived";
for(var j = 0; j < aDiv.length; j++) {
aDiv[j].className = "hide";
}
aDiv[this.index].className = "show";
}
}
}
</script>
</head>
<body>
<div id="lists" class="field">
<ul id="tab">
<li class="actived">房产</li>
<li>家居</li>
<li>二手房</li>
</ul>
<div>
<br/><p>275万购昌平邻铁三居 总价20万买一居</p>
<p>200万内购五环三居 140万安家东三环</p>
<p>北京首现零首付楼盘 53万购东5环50平</p>
<p>京楼盘直降5000 中信府 公园楼王现房</p>
</div>
<div class="hide">
<br/><p>40平出租屋大改造 美少女的混搭小窝</p>
<p>经典清新简欧爱家 90平老房焕发新生</p>
<p>新中式的酷色温情 66平撞色活泼家居</p>
<p>瓷砖就像选好老婆 卫生间烟道的设计</p>
</div>
<div class="hide">
<br/><p>通州豪华3居260万 二环稀缺2居250w甩</p>
<p>西3环通透2居290万 130万2居限量抢购</p>
<p>黄城根小学学区仅260万 121平70万抛!</p>
<p>独家别墅280万 苏州桥2居优惠价248万</p>
</div>
</div>
</body>
</html>
实际效果