jQuery如果div有一个'in'类改变另一个div的背景颜色

时间:2016-04-24 08:36:23

标签: javascript jquery html css twitter-bootstrap

如果div .panel-heading中的.panel-collapse具有.panel类,我想将div类in的背景设为蓝色。我正在使用Bootstrap手风琴。

这是我的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 -->

我尝试过像这样简单的东西,但它不起作用:

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

3 个答案:

答案 0 :(得分:1)

.panel-heading.panel-collapse的兄弟姐妹。尝试使用 siblings() 方法。

$('.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

答案 1 :(得分:1)

试试这个:

$(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 弗雷德里克

答案 2 :(得分:0)

好的,唐:

$(function(){

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

});

在css中添加:

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

它的工作,我希望它是你想要的, - ) 弗雷德里克