Bootstrap 3 折叠菜单:点击后更改箭头图标

42

我已阅读所有关于我的问题的相关问题,并尝试了它们,但均无效。即使我“认为”我写的几乎每一行代码与此网站上发布的解决方案都相同,但似乎我无法让我的代码工作。

这是 HTML 代码:

<div class="press-title">
  <p class="text" data-toggle="collapse" data-target="#serviceList">
    <span id="servicesButton" data-toggle="tooltip " data-original-title="Click Me!">
      <span class="servicedrop glyphicon glyphicon-chevron-down"></span> Services Offered <span class="servicedrop glyphicon glyphicon-chevron-down"></span>
    </span>
  </p>
</div>
<div id="serviceList" class="collapse">
  <div class="row featurette">
  ...

这是 JQuery 的代码

$('#serviceList').on('shown.bs.collapse'), function() {
    $(".servicedrop").addClass('glyphicon-chevron-up').removeClass('glyphicon-chevron-down');
  }

$('#serviceList').on('hidden.bs.collapse'), function() {
    $(".servicedrop").addClass('glyphicon-chevron-down').removeClass('glyphicon-chevron-up');
  }

我只想在折叠元素时将图标从下向上更改,然后在再次点击相同类时切换回来。 我真的被卡住了。 预先感谢您!


shown.bs.collapsehidden.bs.collapse是什么? - Itay
它来自这里。http://getbootstrap.com/javascript/#collapse - Dominic
12个回答

155

纯CSS。

HTML部分:

   <a data-toggle="collapse" href="#collapseExample" 
      aria-expanded="false" aria-controls="collapseExample">
        Open/Close collapse
        <i class="fa fa-chevron-right pull-right"></i>
        <i class="fa fa-chevron-down pull-right"></i>
    </a>

这里的关键元素是aria-expanded="false"或者"true"

CSS:

a[aria-expanded=true] .fa-chevron-right {
   display: none;
}
a[aria-expanded=false] .fa-chevron-down {
   display: none;
}

12
在我看来,这是最好的解决方案。非常巧妙。 - Petercopter
1
最佳解决方案!思路很好。 - David J. Davis
1
我实际上更喜欢这个解决方案。 - GunWanderer
1
简单、清晰易读总是最好的选择……这也是我认为最佳解决方案的原因! - John Contarino
1
这是如此基本、简单和完美,它应该成为 Bootstrap 本身的一部分。赞! - Alex
显示剩余2条评论

26

问题在于您的jQuery代码不正确。

您在此行上过早地关闭了事件处理程序函数:

$('#serviceList').on('shown.bs.collapse'), function() {

看到第二个右括号了吗?那是提前关闭'on'函数的。尝试将您的jQuery更改为:

$('#serviceList').on('shown.bs.collapse', function() {
    $(".servicedrop").addClass('glyphicon-chevron-up').removeClass('glyphicon-chevron-down');
  });

$('#serviceList').on('hidden.bs.collapse', function() {
    $(".servicedrop").addClass('glyphicon-chevron-down').removeClass('glyphicon-chevron-up');
  });

成功了!非常感谢!我还不太熟悉 JQuery,因此犯了一些业余错误。感谢您的时间! :) - Dominic
1
在这里查看纯CSS解决方案:https://dev59.com/22Mk5IYBdhLWcg3wtgMR#33496943 - Andrew

25

尝试这个更优雅的解决方案:

$('#serviceList').click(function(){
    $(this).find('.servicedrop').toggleClass('icon-chevron-down icon-chevron-up');
});

12

与 Bojan 的答案类似,我也使用这个解决方案。
修改 HTML 代码如下:

<span class="chevron_toggleable glyphicon glyphicon-chevron-down"></span>

使用 .on 事件比使用 .click 更好。同时,使用类选择器可以作为整个站点的解决方案。

$('.chevron_toggleable').on('click', function() {
    $(this).toggleClass('glyphicon-chevron-down glyphicon-chevron-up');
});

你好,它已经工作了,但是我看到的不是图标,而是问号图标。你知道为什么吗? - Sasha
我希望用户能够点击整个面板标题来展开/折叠,所以我使用了您的示例,但是将单击事件放在包含面板标题的div上。+1-感谢您提供的好示例。 - Jim
我喜欢这个例子,但出于某种原因它错过了点击(所以它会扩展但不改变图标)。没有错误,我不知道是什么原因导致了这个问题。 - Travis Tubbs

12

纯CSS,甚至代码更少+动画。

HTML部分:

   <a data-toggle="collapse" href="#collapseExample" 
      aria-expanded="false" aria-controls="collapseExample">
        Open/Close collapse
        <i class="fa fa-chevron-right pull-right"></i>
    </a>

CSS:

a[aria-expanded=true] .fa-chevron-right {
 transition: .3s transform ease-in-out;
 transform: rotate(90deg);
}

1
不错!谢谢分享。我的调整:从 aria-expanded=true 开始,使用 chevron-down,然后执行 rotate(180deg),这样我就可以将其指向下方而没有内容。 - Steve Greene
不错,实现简单易懂! - Travis
很好的补充是,如果我们想让尖括号返回,我们可以复制相同的样式并更改 aria-expanded=falserotate(0deg)。这样它就会平滑地返回到初始位置。 - jean d'arme

6
我想提供一个类似于这里发布的另一个解决方案的选项,但使用单个包含转换的 div。这也有助于干净利落地使用过渡来动画化图标。
a[aria-expanded=true] .fa-chevron-right {
   transform: rotate(0deg);
}

a[aria-expanded=false] .fa-chevron-right {
   transform: rotate(90deg); // or whatever direction you need
}

1
这是一个很棒的解决方案,不需要任何额外的JS代码。 - kord

2
你可以尝试这个。
以下是HTML代码:
<a data-toggle="collapse" data-parent="#accordion" href="#collapseOne" aria-expanded="false" aria-controls="collapseOne"> Collapsible Group Item #1<span class="glyphicon glyphicon-chevron-up"></span> </a>

这是 JQuery。
$('#accordion').on('shown.bs.collapse hidden.bs.collapse', function (e) {
         $(e.target).prev('.panel-heading').find("span.glyphicon").toggleClass('glyphicon-chevron-up glyphicon-chevron-down',200, "easeOutSine" );
});

解释一下会很好! - gsamaras

2
我能找到的最简单的答案,我认为将其添加到这里对其他人有用。

基本上,这涉及到这个css代码块

/* Rotating glyphicon when expanding/collapsing */
.collapse-chevron .glyphicon {
  transition: .3s transform ease-in-out;
}
.collapse-chevron .collapsed .glyphicon {
  transform: rotate(-90deg);
}

适用于这段HTML代码

<div class="collapse-chevron">
  <a data-toggle="collapse" class="collapsed" href="#collapseFilter">
     <span class="glyphicon glyphicon-chevron-down" aria-hidden="true"></span>
     <strong>link to toggle</strong>
  </a>
  <div class="collapse" id="collapseFilter">
    <p>Some content I want collapsed or expanded</p>
  </div>
</div>

这段代码的Codepen链接:https://codepen.io/anon/pen/PKxzVa

来源:this article

查看文章中的Codepen链接以获取更多示例:https://codepen.io/disjfa/pen/EZdMpe


不错,但在BS 3上有漏洞(它在页面加载时无法呈现chevron-down)(通过codepen编辑已确认)。 - cowbert
@cowbert 你需要确保将正确的类添加到起始的HTML中。在我的示例中,它是折叠的,所以你需要像我一样加上 class="collapsed" ^^ - Inti
1
搞定了,谢谢!早些时候我使用了CSS的aria-expanded属性匹配隐藏Chevron技巧。 - cowbert
太棒了 - 这个甚至在状态之间还有一个额外的小动画 ;) - Inti

1
"修复了通过更改HTML/CSS解决的问题。
HTML:"
<a data-toggle="collapse" href="#doc" class="yt-toggle collapsed">View Doc 
    <i class="fa fa-caret-right fa-fw"></i> 
    <i class="fa fa-caret-down fa-fw"></i>
</a>

CSS:
.yt-toggle.collapsed .fa-caret-down {
  display: none;
}

.yt-toggle.collapsed .fa-caret-right {
  display: inline-block;
}

.yt-toggle .fa-caret-right {
  display: none;
}

1
<div id="accordion">
  <div class="card">
    <div class="card-header" id="headingOne">
      <h5 class="mb-0">
        <button class="btn btn-link" data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
          Collapsible Group Item #1
        </button>
      </h5>
    </div>

    <div id="collapseOne" class="collapse show" aria-labelledby="headingOne" data-parent="#accordion">
      <div class="card-body">
        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
      </div>
    </div>
  </div>
  <div class="card">
    <div class="card-header" id="headingTwo">
      <h5 class="mb-0">
        <button class="btn btn-link collapsed" data-toggle="collapse" data-target="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo">
          Collapsible Group Item #2
        </button>
      </h5>
    </div>
    <div id="collapseTwo" class="collapse" aria-labelledby="headingTwo" data-parent="#accordion">
      <div class="card-body">
        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
      </div>
    </div>
  </div>
  <div class="card">
    <div class="card-header" id="headingThree">
      <h5 class="mb-0">
        <button class="btn btn-link collapsed" data-toggle="collapse" data-target="#collapseThree" aria-expanded="false" aria-controls="collapseThree">
          Collapsible Group Item #3
        </button>
      </h5>
    </div>
    <div id="collapseThree" class="collapse" aria-labelledby="headingThree" data-parent="#accordion">
      <div class="card-body">
        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
      </div>
    </div>
  </div>
</div>


<script>    

$('.card-header').click(function(){
        $cur = $(this);
        setTimeout(function(){ 
            $('.far').removeClass("fa-minus-square").addClass("fa-plus-square");
            if($cur.next().hasClass("show")) {
                //console.log('show');
                $cur.find('.far').removeClass("fa-plus-square").addClass("fa-minus-square");
            } else {
                //console.log('no show');
                $cur.find('.far').removeClass("fa-minus-square").addClass("fa-plus-square");
            }
        }, 500);


    });
    </script>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接