选项卡
思路:
当点击按钮4时,让1,2,3的样式为空,且4对应的盒子的display为block,其余为none
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
input{
background: #9A99FF;
}
.active{
color: #D44B28;
background: #D9E1F6;
}
div{
width: 200px;
height: 200px;
background: #ccc;
display: none;
}
</style>
</head>
<body>
<input type="button" name="" id="" value="1" />
<input type="button" name="" id="" value="2" />
<input type="button" name="" id="" value="3" />
<input type="button" name="" id="" value="4" />
<div>
111
</div>
<div>
222
</div>
<div>
333
</div>
<div>
444
</div>
<script type="text/javascript">
window.onload = function() {
var aInput = document.getElementsByTagName('input');
var aDiv = document.getElementsByTagName('div');
//默认第一个按钮和对应盒子显示
aInput[0].className = 'active';
aDiv[0].style.display = 'block';
//遍历每一个按钮
for(var i = 0; i < aInput.length; i++) {
//设置当前按钮的索引值,赋值为i
aInput[i].index = i;
//给每个按钮添加点击事件
aInput[i].onclick = function(){
//1.首先将所有的按钮和盒子的样式设置成未点击的状态,既按钮样式为空,盒子变成隐藏
for(var i = 0; i < aInput.length; i++) {
aInput[i].className = '';
aDiv[i].style.display = 'none';
}
//2.再将当前点击的按钮和对应的盒子的样式设成点击状态
this.className = 'active';
aDiv[this.index].style.display = 'block';
//3.不能将aDiv[this.index].style.display = 'block';写成this.style.display = 'block';因为当前点击事件的对象是按钮aInput,非盒子aDiv,所以在进入点击事件前,就设置了每个按钮的索引,当进入点击事件时,该索引值就是当前点击按钮的下标,也就是对应盒子的下标。既this.index = 下标
};
}
};
</script>
</body>
</html>
js思路:
1.首先将所有的按钮和盒子的样式设置成未点击的状态,既按钮样式为空,盒子变成隐藏;
2.再将当前点击的按钮和对应的盒子的样式设成点击状态;
3.不能将aDiv[this.index].style.display = ‘block’;写成this.style.display = ‘block’;因为当前点击事件的对象是按钮aInput,非盒子aDiv,所以在进入点击事件前,就设置了每个按钮的索引,当进入点击事件时,该索引值就是当前点击按钮的下标,也就是对应盒子的下标。既this.index = 下标。