主要用到了排他思想: 干掉所有人,保留我自己。
实现思路: 1.循环为每个li添加自定义属性index索引; 2.为每个li添加click事件,点击之后将所有的li背景色取消,之后再给所点击的li添加背景色; 3.同时将所有内容区域隐藏,再根据索引index将li下面对应的内容区域展现出来。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{
margin: 0;
padding: 0;
}
li{
list-style: none;
}
.tab{
width: 500px;
height: 400px;
margin: 100px auto;
}
.tab_list{
width: 100%;
height: 36px;
background-color: #f7f7f7;
border: 1px solid #eee;
border-bottom: 1px solid #e4393c;
}
.current {
background-color: #e4393c;
color: #fff;
}
.tab_list li{
font: 14px Microsoft YaHei;
display: inline-block;
padding:9px 25px;
}
.tab_list li:hover{
cursor: pointer;
}
.tab_con{
width: 100%;
height: 360px;
border: 1px solid #eee;
border-top: none;
}
.tab_con .item{
height: 100%;
display: none;
font-size: 13px;
text-indent: 13px;
}
</style>
</head>
<body>
<div class="tab">
<div class="tab_list">
<ul>
<li class="current">大春</li>
<li>夏洛</li>
<li>秋雅</li>
<li>冬梅</li>
<li>冬雨</li>
</ul>
</div>
<div class="tab_con">
<div class="item" style="display:block;">
春
</div>
<div class="item">
夏
</div>
<div class="item">
秋
</div>
<div class="item">
冬
</div>
<div class="item">
冬雨
</div>
</div>
</div>
<script>
let lis = document.querySelector('.tab_list').querySelectorAll('li');
let divs = document.querySelector('.tab_con').querySelectorAll('div');
for (let i=0;i<lis.length;i++){
lis[i].setAttribute('index',i);
lis[i].onclick = function(){
for (let j=0;j<lis.length;j++){
lis[j].className = '';
}
this.className = 'current';
for (let k=0;k<divs.length;k++){
divs[k].style.display = 'none';
}
let index = this.getAttribute('index');
divs[index].style.display = 'block';
}
}
</script>
</body>
</html>
|