DOM操作TOP选项卡案例
<style>
.box{
width: 500px;
height: 300px;
border: 1px solid #000;
margin: 50px auto;
}
.box ul{
list-style: none;
padding: 0;
margin: 0;
height: 50px;
display: flex;
justify-content: space-around;
align-items: center;
}
.box ul li{
width: 100px;
height: 30px;
font-weight: bold;
text-align: center;
line-height: 30px;
background-color: pink;
cursor: pointer;
}
.box ol{
list-style: none;
padding: 0;
margin: 0;
}
.box ol li img{
width: 500px;
height: 250px;
}
.box ol li{
display: none;
}
.box ol li.active{
display: block;
}
.box ul li.on{
background-color: #f00;
color: #fff;
}
</style>
<body>
<div class="box">
<ul>
<li class="on">图片1</li>
<li>图片2</li>
<li>图片3</li>
</ul>
<ol>
<li class="active"> <img src="./images/1.webp" /> </li>
<li> <img src="./images/2.webp" /> </li>
<li> <img src="./images/3.webp" /> </li>
</ol>
</div>
</body>
<script>
// 获取文本li
var ulis = document.querySelectorAll('.box ul li')
// 获取图片li
var olis = document.querySelectorAll('.box ol li')
// 遍历
for(var a=0; a<ulis.length; a++) {
function fn(a) {
// 给每个li添加事件
ulis[a].onclick = function() {
// 将之前的on类名去掉
// 将所有li的on类名去掉
// ulis[0].className = ''
// ulis[1].className = ''
// ulis[2].className = ''
// 通过循环处理重复代码
for(var b=0; b<ulis.length; b++) {
ulis[b].className = ''
}
// 输出ulis[a]调试
// console.log(ulis[a]); // undefined - ulis不对或a不对
// console.log( ulis, a ); // a有问题,值为3 - 循环结束后输出a,循环结束后a为3
// 解决:给添加事件的代码外面嵌套一个作用域
// 给当前li添加on类名
ulis[a].className = 'on' // 给标签设置className属性,值为on
// 不能在undefinded上设置className属性
// 言外之意,就是说ulis[a]是undefined
// 将所有图片li的类名去掉
for(var b=0; b<olis.length; b++) {
olis[b].className = ''
}
// 让下标a的图片li添加active
olis[a].className = 'active'
}
}
fn(a)
}
</script>