更改非活动类活动类并仅应用所选元素

时间:2016-05-05 06:24:30

标签: jquery

在给定的示例中,我使用了.inactive类未选择链接元素,我想将.inactive转换为.active并应用于活动链接元素,意味着列表中只有一个.active。

HTML:

<div class="tab-header clearfix">
  <ul id="tabs">
    <li><a id="tab1">About the App</a></li>
    <li><a id="tab2">PLO</a></li>
    <li><a id="tab3">Prerequisites</a></li>
  </ul>
</div>

<div class="tab-container" id="tab1C">
  tab-container 1
</div>

<div class="tab-container" id="tab2C">
  tab-container 2
</div>

<div class="tab-container" id="tab3C">
  tab-container 3
</div>

CSS:

.tab-header {
  background: white;
  border-bottom: 1px solid #ededed;
}
.tab-header #tabs {
  width: 100%;
  height: 30px;
}
.tab-header #tabs li {
  float: left;
  list-style: none;
  width: 30%;
  box-sizing: border-box;
}
.tab-header #tabs li a {
  color: #ffffff;
  padding: 0 5px;
  display: block;
  text-decoration: none;
  outline: none;
  text-align: center;
  line-height: 30px;
  font-size: 13px;
  cursor: pointer;
  background: blue;
}
.tab-header #tabs li a.inactive {
  color: blue;
  background: white;
}
.tab-header .tab-container {
  clear: both;
  width: 100%;
  padding-top: 20px;
}

jQuery:

$('#tabs li a:not(:first)').addClass('inactive');
                $('.tab-container').hide();
                $('.tab-container:first').show();

                $('#tabs li a').click(function(){
                    var t = $(this).attr('id');
                    if($(this).hasClass('inactive')){ //this is the start of our condition 
                    $('#tabs li a').addClass('inactive');           
                    $(this).removeClass('inactive');

                    $('.tab-container').hide();
                    $('#'+ t + 'C').fadeIn('slow');
                 }
                });

JSFiddle Here

2 个答案:

答案 0 :(得分:1)

试试这个

$('#tabs li a').click(function(){
      var t = $(this).attr('id');

      if(!$(this).hasClass('active')){ //this is the start of our condition 

                    $('#tabs li a').removeClass('active').addClass('inactive');           
                    $(this).removeClass('inactive').addClass('active');

                    $('.tab-container').hide();
                    $('#'+ t + 'C').fadeIn('slow');
                 }
                });

https://jsfiddle.net

答案 1 :(得分:0)

你是说这样的意思吗?

当您单击某个选项卡时,此函数会将inactive类添加到没有类inactive的每个选项卡。然后,从所有这些中删除active类。最后,从您单击的标签中删除inactive类,并将其与活动类

一起添加
 $('#tabs li a').click(function(){
      var t = $(this).attr('id');
      $('#tabs li a').click(function(){
             $('#tabs li a:not(.inactive)').addClass("inactive");
             $('#tabs li a').removeClass("active");
             $(this).removeClass("inactive");
             $(this).addClass("active");
      });
 });