日期:2014-05-16  浏览次数:20405 次

用JS制作tab选项卡效果

例子如下:


代码如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<style type="text/css">
div{width:300px; height:200px;border:1px solid #000; display:none;}
.active{background:yellow;}
</style>
<script type="text/javascript">
window.onload=function(){
var aBtn=document.getElementsByTagName('input');
var aDiv=document.getElementsByTagName("div");
//alert(aBtn.length);
//alert(aDiv.length);
for(var i=0;i<aBtn.length;i++){
//给每个按钮,增加一个自定义的属性,名称为 index 它的值就是按钮的编号  
aBtn[i].index=i;

aBtn[i].onclick=function(){
//当点击这个按钮时,将所有的按钮类去掉
for(var i=0;i<aBtn.length;i++){
aBtn[i].className="";
}
//再给当前按钮加类
this.className="active";
//让div集合中的第一个div,显示
//aDiv[1].style.display="block";
//到底让那个div显示,是根据当前点击的按钮编号(集合的索引值)
//aDiv[?].style.display="block";
//alert("当前按钮的索引值是:\n"+aBtn[2].index);
//alert("当前按钮的索引值是:\n"+aBtn[this.index].index);




//先将所有div都隐藏
for(var i=0;i<aDiv.length;i++){
aDiv[i].style.display="none";
}
//,再显示当前相对应的div
aDiv[this.index].style.display="block";


}
}
}
</script>
</head>


<body>
<input type="button" value="新闻" class="active" />
    <input type="button" value="娱乐" />
    <input type="button" value