【发布时间】:2019-07-12 03:52:00
【问题描述】:
我有三个“li”标签和一个 showTab“div”。
我希望单击的选项卡显示在 showTab 中,这工作正常,但我还想将活动类添加到单击的选项卡,并将 inActive 类添加到未单击的其他选项卡(兄弟)。
一个标签应该总是有活动的类。
我是 Javascript 的新手,请原谅我的无知。
这是我的代码的链接: code
我之前在 jQuery 中尝试过这个,我现在想要达到的效果与此类似:
$(this).addClass('active');
$(this).siblings('.tabs').removeClass('active');
HTML
<div class="tab-container">
<div class="showtab active">
<img class='showtabimg' src="" alt="showtabimg">
</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" alt="foto3" class='img'>
</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 !important;
opacity: 1 !important;
}
.inActive{
color: blue;
border: 1px solid blue;
opacity: .3;
}
JS
var tabs = document.querySelector('.tabs');
var tab = document.querySelectorAll('.tab');
var showTab = document.querySelector('.showtab');
var img = document.querySelector('.showtabimg');
tab.forEach(thumbNail => {
thumbNail.addEventListener('click',function(item){
var content = item.target.getAttribute("src");
this.classList.toggle('active')
img.setAttribute('src', content);
} );
});
【问题讨论】:
-
嗯,从逻辑上讲,您可以简单地添加
inActive类并删除active到所有tab,然后添加active类并删除inActive类单击的元素。您可能会发现将它们默认设置为非活动状态更容易,然后您可以切换活动类。
标签: javascript dom-events