简体   繁体   中英

Less - Mixin a class that is attached to a parent

For some context, I am using bootstrap nav pills as triggers for bootstrap collapsibles .

This is what bootstraps less for nav pills looks like (simplified)

.nav-pills {
  > li {    
    // Active state
    &.active > a {
      &,
      &:hover,
      &:focus {
        color: @nav-pills-active-link-hover-color;
        background-color: @nav-pills-active-link-hover-bg;
      }
    }
  }
}

When a collapsible is collapsed, it adds a collapsed class to the trigger (the .nav-pills > li element in this case). What I am trying to do, is simply apply the .active class to the nav pill when it doesn't have the class .collapsed .

I tried to do

:not(.collapsed) { .active; }
:not(.collapsed) { &:extend(.active); }
:not(.collapsed) { &:extend(.active all); }

But none of them would yield the results I wanted. The first one wouldn't even compile.

Is there a way to achieve this?

update

@import (reference) "bower_components/bootstrap/less/bootstrap.less";

.nav-pills {
  > li > a:not(.collapsed) {
  &:extend(.nav-pills > li.active > a all);
}
}

outputs:

.nav-pills > li > a:not(.collapsed),
.nav-pills > li > a:not(.collapsed):hover,
.nav-pills > li > a:not(.collapsed):focus {
  color: #ffffff;
  background-color: #337ab7;
}

It seems that a:not(.collapsed) not matches a without a class atribute so you so initiate your HTML with class="collapsed" :

<ul class="nav nav-pills">
  <li role="presentation"><a class="collapsed" data-toggle="collapse" data-parent="#tabs" href="#tab1">Tab 1</a></li>
  <li role="presentation"><a class="collapsed" data-toggle="collapse" data-parent="#tabs" href="#tab2">Tab 2</a></li>
  <li role="presentation"><a class="collapsed" data-toggle="collapse" data-parent="#tabs" href="#tab3">Tab 3</a></li>
</ul>

end update

I'm not sure if i understand your question well. I think you could possible use the collapse events and jQuery:

$('#tabs').on('show.bs.collapse', function (event) 
{
  $('[href="#' + $(event.target).attr('id') + '"]').parent().addClass('active'); 
});
$('#tabs').on('hide.bs.collapse', function (event) 
{
  $('[href="#' + $(event.target).attr('id') + '"]').parent().removeClass('active'); 
});

Demo: http://www.bootply.com/WvpaNi4LlZ

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM