我想实现的是一个简单的选项卡函数。
我有3个图像和一个Div Showtab。
当我单击其中一个图像时,单击的图像应为活动类,并在Showtabdiv中显示和其他图像,应参加不活动的类。
我完全是JavaScript的新手,所以请原谅我的无知。
目前,我的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);
});
这是jsfiddle中的演示:
.querySelector()
函数仅返回第一个匹配元素。您可以改用.querySelectorAll()
,然后通过返回的列表迭代:
var tabs = document.querySelectorAll(".tab");
tabs.forEach(tab => {
tab.addEventListener( ... );
});