<!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;
list-style: none;
}
li {
width: 100px;
height: 80px;
border: 1px solid grey;
float: left;
background-color: white;
margin-left: -1px;
}
.red {
background-color: red;
}
.zi {
clear: left;
}
.bl {
display: block;
}
.no {
display: none;
}
</style>
</head>
<body>
<div>
<ul>
<li class="red"></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>
<div class="zi">
<div class="item">11111</div>
<div class="item">22222</div>
<div class="item">33333</div>
<div class="item">44444</div>
</div>
<script>
let li = document.querySelectorAll("li")
let div = document.querySelectorAll(".item")
// 获取元素
for (i = 0; i < li.length; i++) {
// 遍历li
li[i].setAttribute("index", i)
// 给每个li设置编号
li[i].onclick = function () {
// li点击事件
for (i = 0; i < li.length; i++) {
li[i].className = " "
// 遍历数组,使每个li属性为空,即消除背景色
}
this.className = "red"
// 给点击的数组添加属性:背景色红色
let index=this.getAttribute("index")
// 获取当前点击的li编号
for(i=0;i<div.length;i++){
div[i].className = "no"
// 遍历数组,使每个item隐藏,即都不显示
}
div[index].className = "bl"
// 给点击的item设置显示
}
}
</script>
</body>
</html>
JS小练————tab栏切换(含注释)
最新推荐文章于 2024-08-31 13:05:07 发布