1

我有三个“li”标签和一个 showTab“div”。

我希望单击的选项卡显示在 showTab 中,这工作正常,但我还想将活动类添加到单击的选项卡,并将 inActive 类添加到未单击的其他选项卡(兄弟)。

一个选项卡应始终具有活动类。

我对 Javascript 完全陌生,所以请原谅我的无知。

这是我的代码的链接: 代码

我之前在 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);


  } );
});
4

1 回答 1

0

我想你想删除点击之外的项目类别

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

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);
  } );
});
于 2019-02-18T17:55:11.333 回答