- 微信扫码关注公众号 :前端前端大前端,追求更精致的阅读体验 ,一起来学习啊
- 关注后发送关键资料,免费获取一整套前端系统学习资料和老男孩python系列课程
代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>tab栏切换</title>
<style>
span {
cursor: pointer;
}
.red {
color: red;
}
</style>
</head>
<body>
<div class="container">
<div class="header">
<span>新闻</span>
<span>体育</span>
<span>娱乐</span>
</div>
<div class="content">
<ul>
<li>新闻新闻</li>
<li>体育体育</li>
<li>娱乐娱乐</li>
</ul>
</div>
</div>
<script>
let spans = document.getElementsByTagName('span');
let lis = document.getElementsByTagName('li');
for (let i = 0; i < spans.length; i++) {
lis[i].style.display = "none";
//为所有span注册点击事件
spans[i].onclick = function() {
//排他功能的实现
for (let j = 0; j < spans.length; j++) {
spans[j].className = "";
}
this.className = "red";
//导航和内容的索引对应
for (let k = 0;k < lis.length;k++) {
lis[k].style.display=(i==k)?"block":"none"
}
}
}
</script>
</body>
</html>