先上代码
css部分
* {
padding: 0;
margin: 0;
}
ul {
list-style: none;
}
#tab {
width: 480px;
margin: 20px auto;
border: 1px solid cornflowerblue;
}
ul {
width: 100%;
overflow: hidden;
}
ul li {
float: left;
width: 160px;
height: 60px;
line-height: 60px;
text-align: center;
background-color: #cccccc;
}
ul li a {
text-decoration: none;
color: black;
}
p {
height: 200px;
text-align: center;
line-height: 200px;
background-color: #fff;
/* 默认所有的图片都隐藏 */
display: none;
}
li.active{
background-color: cornflowerblue;
}
/* 有这个类名的p标签,显示 */
p.active{
display: block;
}
img{
width: 100%;
}
js部分
class Car {
constructor(el) {
this.el = el;
this.lis = el.querySelectorAll("li");
this.ps = el.querySelectorAll("p");
this.init();
}
init(){
var that = this;
for (var i = 0; i < this.lis.length; i++) {
//在遍历li标签,为该元素添加一个自定义属性,用来保存它的下标。
this.lis[i].dataset.index = i;
this.lis[i].onclick = function () {
//在添加之前,将其他所有li标签中的“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++) {
//隐藏图片:将active类名删除
that.ps[k].classList.remove("active")
}
//让对应的图片显示:为它添加active类名。
that.ps[this.index].classList.add("active")
}
}
}
}