需求:
点击界面中按钮,将当前被点击的按钮的背景颜色变为gold色,其他的按钮恢复默认。2、当点击按钮的时候,需要将这个按钮对应位置的div显示出来
提示:让按钮背景颜色变为gold色只需要给按钮的class增加active即可
让div显示出来,只需要将div的class增加current即可
// css 代码
<style>
.tab_con {
width: 500px;
height: 350px;
margin: 50px auto 0;
}
.tab_btns {
height: 50px;
}
.tab_btns input {
width: 100px;
height: 50px;
background: #ddd;
border: 0px;
outline: none;
}
/* .tab_btns input:active {
background: gold;
} */
.tab_btns .active {
background: gold;
}
.tab_cons {
height: 300px;
background: gold;
}
.tab_cons div {
height: 300px;
line-height: 300px;
text-align: center;
display: none;
font-size: 30px;
}
.tab_cons .current {
display: block;
}
</style>
// html 代码
<div class="tab_con">
<div class="tab_btns">
<input type="button" value="按钮一" class="active">
<input type="button" value="按钮二">
<input type="button" value="按钮三">
</div>
<div class="tab_cons">
<div class="current">按钮一对应的内容</div>
<div>按钮二对应的内容</div>
<div>按钮三对应的内容</div>
</div>
</div>
// js代码
<script>
// 获取元素
var tab_btns = document.querySelector('.tab_btns');
var tab_cons = document.querySelector('.tab_cons');
var btns = tab_btns.querySelectorAll('input');
var divs = tab_cons.querySelectorAll('div');
for (var i = 0; i < btns.length; i++) {
// 设置索引号
btns[i].setAttribute('index', i);
btns[i].addEventListener('click', function() {
// 干掉所有
for (var i = 0; i < btns.length; i++) {
btns[i].className = '';
divs[i].className = '';
}
// 点击谁,显示谁,显示自己 当前的小li 设置current 类名
this.className = 'active';
// 获得索引号
var index = this.getAttribute('index');
divs[index].className = 'current';
});
}
</script>