【问题标题】:Add class to active tab && Add class inActive to inactive tab将类添加到活动选项卡 && 将类 inActive 添加到非活动选项卡
【发布时间】: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


【解决方案1】:

我认为您想删除点击范围之外的项目类别

在所有其他操作之前删除所有元素的所有活动元素

tab.forEach(thumbNail => {
  thumbNail.addEventListener('click',function(item){
    // delete all active or normal elements active class
    tab.forEach(i => i.classList.remove('active'))

    var content = item.target.getAttribute("src");

    this.classList.toggle('active')

    img.setAttribute('src', content);
  } );
});

【讨论】:

  • 谢谢Minan,这解决了我的问题。接受为答案。
猜你喜欢
  • 2014-05-16
  • 1970-01-01
  • 2012-10-16
  • 1970-01-01
  • 1970-01-01
  • 2023-04-04
  • 1970-01-01
  • 2017-06-19
  • 1970-01-01
相关资源
最近更新 更多