我想要实现的是一个简单的制表符功能。
我有3张图片和一个div showTab。
当我单击其中一张图像时,单击的图像应采用活动类并在showTab div中显示,而其他图像应采用inActive类。
我完全是Java语言的新手,请原谅我的无知。
目前,只有我ul内部的第一个li工作。 当我单击其他按钮时,其他按钮不会显示。
HTML :
<div class="tab-container">
<div class="showtab active">
</div>
<ul class="tabs">
<li class="tab tab1">
<img src="https://images.unsplash.com/photo-1550364387-ffbad4f8e9b2?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=634&q=80" alt="foto1" class='img'>
</li>
<li class="tab tab2">
<img src="https://images.unsplash.com/photo-1550368759-0fdb22fe8020?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=634&q=80" alt="foto2" class='img'>
</li>
<li class="tab tab3">
<img src="https://images.unsplash.com/photo-1550371554-387863e7bd38?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=634&q=80" class='img inActive'>
</li>
</ul>
</div>
CSS:
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
ul li{
list-style: none;
}
.showtab{
width: 200px;
height: 100px;
color: red;
font-weight: bold;
display: flex;
margin-bottom: 20px;
}
.showtab img{
width: 100%;
}
.tabs{
display: flex;
}
.tabs li{
display: flex;
cursor: pointer;
width: 100px;
height: 100px;
margin-right: 10px;
}
.tabs li img{
width: 100%;
}
.active{
color: red;
border: 1px solid red;
opacity: 1;
}
.inActive{
color: blue;
border: 1px solid blue;
opacity: .3;
}
JS:
var tabs = document.querySelector('.tabs');
var tab = document.querySelector('.tab');
var showTab = document.querySelector('.showtab');
tab.addEventListener('click', function(event){
event.stopPropagation();
var content = event.currentTarget.innerHTML;
tab.classList.add('active');
showTab.classList.add('active');
showTab.innerHTML = content;
console.log(this);
});
答案 0 :(得分:1)
.querySelector()
函数仅返回第一个匹配的元素。您可以改用.querySelectorAll()
,然后遍历返回的列表:
var tabs = document.querySelectorAll(".tab");
tabs.forEach(tab => {
tab.addEventListener( ... );
});