<!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>选项卡</title>
<style>
* {
padding: 0;
margin: 0;
}
.container {
width: 450px;
height: 500px;
border: 1px solid rgb(133, 131, 131);
margin: 10px auto;
display: flex;
flex-direction: column;
}
.container ul {
display: flex;
justify-content: space-around;
}
ul li {
list-style: none;
border: 1px solid rgb(175, 175, 175);
width: 150px;
height: 50px;
line-height: 50px;
text-align: center;
background-color: rgb(179, 205, 255);
cursor: pointer;
}
ol li {
display: none;
}
img {
height: 448px;
width: 450px;
}
/* 当鼠标点击时,背景颜色变化 */
.active {
background-color: rgb(223, 255, 210);
}
/* 当鼠标点击时,图片由隐藏转为可见 */
.on {
display: block;
}
</style>
</head>
<body>
<div class="container">
<ul>
<li data-index="0">选项一</li>
<li data-index="1">选项二</li>
<li data-index="2">选项三</li>
</ul>
<ol>
<!-- 与上面的ul是一一对应的 -->
<li><img src="images/1.jpeg" alt="pic"></li>
<li><img src="images/2.jpeg" alt="pic"></li>
<li><img src="images/3.jpg" alt="pic"></li>
</ol>
</div>
<script>
var ulLiEles = document.querySelectorAll('ul>li')
var olLiEles = document.querySelectorAll('ol>li')
// 当点击事件发生时添加样式
for (var i = 0; i < ulLiEles.length; i++) {
ulLiEles[i].onclick = function () {
// 先清除样式
removeClassStyle()
// 再添加样式
// 用this表示当前点击元素
this.classList.add('active')
var index = this.getAttribute('data-index')
olLiEles[index].classList.add('on')
}
}
// 清除样式
function removeClassStyle() {
for (var i = 0; i < ulLiEles.length; i++) {
ulLiEles[i].classList.remove('active')
olLiEles[i].classList.remove('on')
}
}
</script>
</body>
</html>
效果:
|