<style>
* {
margin: 0;
padding: 0;
}
li {
list-style: none;
text-align: center;
}
a {
text-decoration: none;
line-height: 50px;
color: black;
display: block;
}
.box {
width: 400px;
height: 400px;
/* border: 1px solid red; */
margin: 0 auto;
}
.box ul {
display: flex;
}
.box li {
width: 140px;
height: 50px;
background-color: cadetblue;
}
li.active {
background-color: cornflowerblue;
}
img {
width: 400px;
height: 250px;
}
.box p {
font-size: 0;
display: none;
}
p.active {
display: block;
}
</style>
</head>
<body>
<div class="box">
<ul>
<li class="active">
<a href="Javascript:;">云景</a>
</li>
<li>
<a href="#">雪景</a>
</li>
<li>
<a href="#">湖景</a>
</li>
</ul>
<p class="active"><img src="./img/showpic01.jpg" alt=""></p>
<p><img src="./img/showpic02.jpg" alt=""></p>
<p><img src="./img/showpic03.jpg" alt=""></p>
</div>
<script>
class Cut {
constructor(el) {
this.el = el
this.lis = el.querySelectorAll('li');
this.ps = el.querySelectorAll('p');
this.Click();
}
Click() {
/* 为所有li添加事件 */
var that = this
for (var i = 0; i < this.lis.length; i++) {
this.lis[i].dataset.index = i;
/* 添加点击事件 */
this.lis[i].onclick = function() {
/* 所有active类名删除 */
for (var j = 0; j < that.lis.length; j++) {
that.lis[j].classList.remove('active')
}
//谁被点击,就为谁添加类名
// this 关键字, 在当前函数中,谁被点击了,this就指向谁。
this.classList.add('active')
this.index = this.dataset.index;
for (var k = 0; k < that.ps.length; k++) {
that.ps[k].classList.remove('active');
}
that.ps[this.index].classList.add('active')
}
}
}
}
/* 获取容器 */
var box = document.querySelector('.box')
/* 调用 */
new Cut(box);
</script>
</body>