选项卡这个效果在实际项目中经常会用到,这里写一个简单的Tab选项卡,来讲解一下制作思路和代码编写。
效果展示:

设计思路:
选项卡就是点击按钮切换到相应内容,其实就是点击按钮把内容通过display(block none)来实现切换的。
1、首先获取元素。
2、for循环历遍按钮元素添加onclick 或者 onmousemove事件。
3、因为点击当前按钮时会以高亮状态显示,所以要再通过for循环历遍把所有的按钮样式设置为空和把所有DIV的display设置为none。
4、把当前按钮添加样式,把当前DIV显示出来,display设置为block。
注:给多个元素添加多个事件要用for循环历遍。如选项卡是点击切换,当前按钮高度,点击和按钮高亮就是2个事件,所以要用2个for循环历遍。
代码的实现:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>选项卡_01</title>
<style type="text/css">
*{padding:0;margin:0}
ul li{list-style:none}
.tab{width:500px;margin:20px auto;}
.hide{display:none;}
.tab-head{height:25px;border-bottom:1px solid #ccc;}
.tab-head li{float:left;width:80px;height:24px;line-height:24px;margin-right:4px;text-align:center;border:1px solid #ccc;border-bottom:none;background:#f5f5f5;cursor:pointer;}
.tab-head .act{position:relative;height:25px;margin-bottom:-1px;background:#fff;}
.tab-inner{border:1px solid #ccc;border-top:none;padding:20px;}
</style>
</head>
<body>
<div class="tab">
<ul class="tab-head" id="tab_head">
<li class="tab-t act">选择1</li>
<li class="tab-t">选择2</li>
</ul>
<div class="tab-inner" id="tab_inner">
<div class="tab-c">内容1</div>
<div class="tab-c hide">内容2</div>
</div>
</div>
<script type="text/javascript">
window.onload=function(){
var tab_h=document.getElementById('tab_head');
var tab_t=tab_h.getElementsByClassName('tab-t');
var tab_i=document.getElementById('tab_inner');
var tab_c=tab_i.getElementsByClassName('tab-c');
var len=tab_t.length;
var i=0;
for(i=0;i<len;i++){
tab_t[i].index=i;
tab_t[i].onclick=function(){
for(i=0;i<len;i++){
tab_t[i].className='tab-t';
tab_c[i].className='tab-c hide';
}
tab_t[this.index].className='tab-t act';
tab_c[this.index].className='tab-c';
}
}
}
</script>
</body>
</html>
星之书笔记