<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
div{
width: 200px;
height: 200px;
border: 1px solid #000;
position: absolute;
top: 50px;
font-size: 50px;
text-align: center;
line-height: 200px;
display: none;
}
div:nth-child(4){
display: block;
}
</style>
<body>
<button>按钮1</button>
<button>按钮2</button>
<button>按钮3</button>
<div>内容1</div>
<div>内容2</div>
<div>内容3</div>
<script>
// 效果: 点击每一个按钮, 出现对应的div
var btns = document.getElementsByTagName('button');
var divs = document.getElementsByTagName('div');
console.log(btns, divs);
// 一一对应
// 每一个按钮添加点击事件
for(var i = 0; i < btns.length; i++){
btns[i].index = i;
btns[i].onclick = function(){
// 点击的时候如果只有一个元素需要保持新的状态,但是不知道上一次点击的元素是谁
// 先将所有的按钮的状态清空,回归到初始的默认值
// 排他
// 先把所有的回归到默认状态, 然后再给当前的元素添加
for(var j = 0; j < btns.length; j++){
btns[j].style.background = '';
divs[j].style.display = 'none';
}
// 让对应的div显示, 让自己的背景色变红
// 获取索引
console.log(this.index);
divs[this.index].style.display = 'block';
this.style.background = 'red';
}
}
</script>
</body>
</html>