优化前:
<style>
ul {
list-style: none;
width: 600px;
display: flex;
height: 50px;
}
li {
flex: 1;
background-color: #ccc;
border-right: 1px solid blue;
line-height: 50px;
text-align: center;
}
.active {
background-color: orange;
}
</style>
</head>
<body>
<ul class="list">
<li>首页</li>
<li>文章列表</li>
<li class="active">发表文章</li>
<li>关于我们</li>
</ul>
<script>
// 1.获取元素
let lis = document.querySelectorAll('li')
// 2.遍历伪数组,为其中的每个元素绑定单击事件
for (let i = 0; i < lis.length; i++) {
lis[i].addEventListener('click', function() {
// 3.1 干掉所有元素的active样式
lis.forEach(function(ele, index) {
ele.classList.remove('active')
})
// 3.2 为当前元素添加active样式
// lis[i].classList.add('active')
this.classList.add('active')
})
}
</script>
优化后:移除遍历 找到当前有active样式的li元素,清除它的active样式
<style>
ul {
list-style: none;
width: 600px;
display: flex;
height: 50px;
}
li {
flex: 1;
background-color: #ccc;
border-right: 1px solid blue;
line-height: 50px;
text-align: center;
}
.active {
background-color: orange;
}
</style>
</head>
<body>
<ul class="list">
<li>首页</li>
<li>文章列表</li>
<li class="active">发表文章</li>
<li>关于我们</li>
</ul>
<script>
// 1.获取元素
let lis = document.querySelectorAll('li')
// 2.遍历伪数组,为其中的每个元素绑定单击事件
for (let i = 0; i < lis.length; i++) {
lis[i].addEventListener('click', function () {
// // 3.1 干掉所有元素的active样式
// lis.forEach(function(ele, index) {
// ele.classList.remove('active')
// })
// 3.1 找到当前有active样式的li元素,清除它的active样式
// li.active:交集选择器:要求它是li元素的同时还要拥有active样式
document.querySelector('li.active').classList.remove('active')
// 3.2 为当前元素添加active样式
// lis[i].classList.add('active')
this.classList.add('active')
})
}
</script>