源代码

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>选项卡</title>
<style>
#div1 input {background:#CCC;}
#div1 div {width:200px; height:200px; background:#CCC; display:none;}
#div1 .active {background:yellow;}
#div1 .kin {background:red;}
</style>
<script>
window.onload = function() {
var oDiv = document.getElementById('div1');
var aBtn = oDiv.getElementsByTagName('input');
var aDiv = oDiv.getElementsByTagName('div');
var i = 0; for(i = 0; i < aBtn.length; i++){
// index 属性可返回标签的索引位置
aBtn[i].index = i;
//测试i的索引位置
// alert(i); // 给onclick事件添加自定义方法
aBtn[i].onclick = function() {
for(i = 0; i < aBtn.length; i++){
// 给未点击的按钮添加class="kin"
aBtn[i].className = 'kin';
// 给当前Div的class添加style="display:none"
aDiv[i].style.display = 'none';
}
// 鼠标点击那个按钮就给那个添加class="active"
this.className = 'active';
// 给当前的class添加style="display:block"
aDiv[this.index].style.display = 'block';
};
}
};
</script>
</head>
<body>
<div id="div1">
<input type="button" value="txt1" class="active" />
<input type="button" value="txt2" />
<input type="button" value="txt3" />
<div style="display:block;">txt1content</div>
<div>txt2content</div>
<div>txt3content</div>
</div>
</body>
</html>

运行结果

js面向过程-经典选项卡-LMLPHP

核心代码

1. index属性

作用:返回标签的索引位置

 aBtn[i].index = i;

2.给onclick事件添加自定义方法

aBtn[i].onclick = function() {
  for(i = 0; i < aBtn.length; i++){
    aBtn[i].className = 'kin';
    aDiv[i].style.display = 'none';
  }
 
  this.className = 'active';
  aDiv[this.index].style.display = 'block';
};
05-11 11:37