<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>显卡切换</title>
<style>
.box{
margin: 0 auto;
width: 400px;
}
.but{
width: 60px;
height: 40px;
border-radius: 4px;
background: none;
border: 1px solid #9d9d9d;
margin-left: 20px;
outline: none;
}
.but:hover{
border: 1px solid green;
}
.action{
border: 1px solid green;
width: 60px;
height: 40px;
border-radius: 4px;
background: none;
margin-left: 20px;
outline: none;
}
.disnone{
display: none;
width: 330px;
height: 120px;
border: 1px solid #eeeeee;
margin-top: 20px;
text-align: center;
}
.disblock{
display:block;
width: 330px;
height: 120px;
border: 1px solid #eeeeee;
margin-top: 20px;
text-align: center;
}
</style>
</head>
<body>
<section class="box">
<section class="buts" id="buts">
<button class="but action">按钮1</button>
<button class="but">按钮2</button>
<button class="but">按钮3</button>
<button class="but">按钮4</button>
</section>
<section class="cont" id="cont">
<section class="disblock">我是按钮1的内容</section>
<section class="disnone">我是按钮2的内容</section>
<section class="disnone">我是按钮3的内容</section>
<section class="disnone">我是按钮4的内容</section>
</section>
</section>
</body>
</html>
<script>
//获取按钮的父盒子
let buts=document.getElementById('buts')
//获取所有按钮
let butbox=buts.getElementsByTagName('button');
//获取内容父盒子
let cont=document.getElementById('cont');
//获取父盒子底下的所有内容
let content=cont.getElementsByTagName('section');
//循环遍历按钮
for(let i=0;i<butbox.length;i++){
//动态添加按钮的index
butbox[i].index=i;
//给每一个按钮添加事件
butbox[i].οnclick=function(){
//重置所有按钮样式
for(let i=0;i<butbox.length;i++){
butbox[i].className='but'
}
//重置所有内容样式
for(let i=0;i<content.length;i++){
content[i].className='disnone'
}
//当前点击的添加样式
this.className='action'
content[this.index].className='disblock'
console.log(content[this.index])
}
}
</script>