简体   繁体   中英

jQuery if div has a class of 'in' change another div's background color

I want to make the background of a div class .panel-heading to blue if the .panel-collapse inside the div .panel has a class of in . I am using Bootstrap accordion.

This is my HTML:

<div class="panel panel-default">
    <div class="panel-heading">
        <h4 class="panel-title">
            <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion" href="#collapseOne">
                Lipsum set dolor
                <span class="pull-right glyphicon glyphicon-minus"></span>
            </a>
        </h4>
    </div>
    <div id="collapseOne" class="panel-collapse collapse in">
        <div class="panel-body">
            Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since
        </div>
    </div>
</div><!-- end panel -->

I tried something simple like this but it is not working:

if ($('.panel-collapse').hasClass('in')) {
    $(this).closest('.panel-heading').css("background", "blue");
}
else {
    $(this).closest('.panel-heading').css("background", "red");
}

.panel-heading is sibling of .panel-collapse . Try like following using siblings() method.

$('.in').siblings('.panel-heading').css("background", "blue");

$('.collapse').on('shown.bs.collapse', function () {
    var panelHeading = $(this).siblings('.panel-heading');
    panelHeading.find(".glyphicon-plus").toggleClass("glyphicon-minus glyphicon-plus");
    panelHeading.css("background", "blue");
}).on('hidden.bs.collapse', function () {
    var panelHeading = $(this).siblings('.panel-heading');
    panelHeading.find(".glyphicon-minus").toggleClass("glyphicon-minus glyphicon-plus");
    panelHeading.css("background", "red");
});

UPDATED FIDDLE

try this :

$(function(){
    $('.panel-collapse').each(function(index,element){
    if($(element).hasClass('in')){
        $(element).prev('.panel-heading').css("background", "blue");
    } else {
        $(element).prev('.panel-heading').css("background", "red");
    }
  });
});

Cordialy Frederic

ok, donc :

$(function(){

    $('.accordion-toggle').on('click',function(e){
    $('.panel-heading').removeClass('bgBlue');
    $(this).closest('div.panel-heading').addClass('bgBlue');
  });

});

in css add :

.bgBlue{
  background-color:blue !important;
}

and it's work, i hope it's what you want ,-) Frederic

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