javascript实现简单的tab选项卡

时间:2022-11-07 06:27:59
<!DOCTYPE html>
<html>

<head>
<meta charset="utf-8" />
<title></title>
<style type="text/css">
button {
width: 120px;
height: 32px;
line-height: 32px;
background-color: #ccc;
font-size: 24px;
}

div {
display: none;
width: 200px;
height: 200px;
font-size: 72px;
color: #ddd;
background-color: green;
border: 1px solid black;
}

.btn-active {
background-color: yellow;
}

.div-active {
display: block;
font-weight: bold;
font-size: 14px;
}
</style>
</head>

<body>
<button class="btn-active">1</button>
<button>2</button>
<button>3</button>
<button>4</button>
<div class="div-active">1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<!--添加className来增减样式,定义index属性来匹配-->
<script type="text/javascript">
var buttonArr = document.getElementsByTagName("button");
var divArr = document.getElementsByTagName("div");
for(var i = 0; i < buttonArr.length; i++) {
buttonArr[i].index = i;
//buttonArr[i].setAttribute("index",i);
buttonArr[i].onclick = function() {
for(var j = 0; j < buttonArr.length; j++) {
buttonArr[j].className = "";
divArr[j].className = "";
}
this.className = "btn-active";
divArr[this.index].className = "div-active";
//divArr[this.getAttribute("index")].className="div-active";
}
}
</script>

</body>

</html>
个人倾向于这种写法,优点在于:
1、通过添加类名或删除类名来添加样式或重置样式,可以做到CSS和javascript分离,后期修改样式只需要修改CSS代码即可。
2、定义index属性返回数组中元素的索引位置。

当然也有如下另一种方法

<!--添加className来增减样式,if判断当前点击与自定义数组是否匹配-->
<script type="text/javascript">
//取出导航节点并循环遍历
var buttonArr = document.getElementsByTagName("button");
var divArr = document.getElementsByTagName("div");
for(var i = 0; i < buttonArr.length; i++) {
buttonArr[i].onclick = function() {
//导航一被点击即进行样式重置
for(var j = 0; j < buttonArr.length; j++) {
buttonArr[j].className = "";

divArr[j].className = "";
//判断此时点击的是哪一个按钮
if(this == buttonArr[j]) {
divArr[j].className = "div-active";
}
}
//给当前点击的button设置样式
this.className = "btn-active";

}
}
</script>