<!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;
}
ul{
list-style: none;
}
.header{
display: flex;
width: 500px;
}
.header li{
flex:1;
height: 50px;
line-height: 50px;
text-align: center;
border: 1px solid black;
}
.box{
position: relative;
}
.box li{
position: absolute;
left: 0;
top: 0;
width: 500px;
height: 200px;
background-color: yellow;
/* 隐藏元素并脱离文档 */
display: none;
}
.header .active{
background-color: red;
}
.box .active{
/* 将行内元素转成块级元素,块级元素一般单独占一行 */
display: block;
}
</style>
</head>
<body>
<ul class="header">
<li class="active">正在热映</li>
<li>即将上映</li>
<li>选择影院</li>
<li>选择时间</li>
</ul>
<ul class="box">
<li class="active">0-没有电影</li>
<li>1-没有上映</li>
<li>2-没有影院</li>
<li>3-没有时间</li>
</ul>
<script>
var oHeaderItems = document.querySelectorAll(".header li")
var oBoxItems = document.querySelectorAll(".box li")
// console.log(oBoxItems)
for(var i=0;i<oHeaderItems.length;i++){
oHeaderItems[i].dataset.index = i
oHeaderItems[i].onclick = handler
}
function handler(){
// console.log("111")//确定是否绑上事件.
// console.log(i)//结果都是4,for早就执行完了,所以都是4.
// 所以需要在for循环执行之前自定义属性,标记li;
// 后面就获取自身的属性.
// console.log(this.dataset.index)//this可以拿到当前点击的对象.
// 不管有没有active,把每一个选项卡上的active都清掉;
// 然后再在点击的那个选项卡上加active.
var index = this.dataset.index//拿到index值
for(var i=0;i<oHeaderItems.length;i++){
oHeaderItems[i].classList.remove("active")
oBoxItems[i].classList.remove("active")
}
oHeaderItems[index].classList.add("active")
oBoxItems[index].classList.add("active")
}
</script>
</body>
</html>
效果显示: