为什么 Jquery .show() 不会在 bootstrap 手风琴折叠中显示锚点 div?

Why won't Jquery .show() display anchor div within bootstrap accordion collapse?

我对网络开发还很陌生。我花了几天时间研究这个(尴尬)并研究了我能想到的一切。

我正在使用 Rails 5、bootstrap 3 和 jquery 2.1.3。

我有一个 bootstrap 手风琴。在各种折叠内容 divs 中,我希望 links 位于同一手风琴但不同折叠面板中的内容。

在当前的折叠面板中,我有一个 link 这样的:

<a class="self-link" href="#buried_sub_anchor">Buried Sub Anchor</a>

在另一个折叠面板中,我有这样的内容 div:

<div class="anchor" id="buried_sub_anchor">

我的 jquery 处理点击的代码是:

  $('.self-link').on('click', function() {expandCollapseWithHash(this.hash); });

  function expandCollapseWithHash(hash) {
    var $collapses = $(hash).parents('.collapse');
    if ($collapses.length > 0) {
      var $collapse = $collapses.first()
      $collapse.collapse('show');
    }
  }

当 .collapse('show') 被调用时,我期待 bootstrap 神奇地关闭当前面板并打开目标。然后,一旦转换完成,我期待 'shown' 事件触发,我这样处理:

  $('.collapse').on('shown.bs.collapse', function() {
    if (location.hash) {
      $(location.hash).show();
    }
  });

我期待 .show() 调用将页面直接跳转到锚定 div。但是没有骰子。

总而言之,当我点击 link 时,我想要:

  1. 当前面板.collapse('hide')
  2. .collapse('show')的目标面板
  3. 要跳转到目标面板中锚定 div 的页面

相反,总是:

  1. 当前面板没有改变(即保持显示)
  2. 目标面板显示
  3. 页面跳转到新位置,但离所需的锚 div 部分不远

我的问题是:

  1. 为什么当前面板没有折叠?我希望 bootstrap 手风琴功能作为 $collapse.collapse('show') 调用的结果来执行此操作。
  2. 为什么页面不滚动到 linked 内容?

Here is a fiddle。重现:

  1. 点击"More Details"部分
  2. 一直向下滚动
  3. 单击 "Buried sub anchor" link

您必须强制 scrollTop 执行此操作。
我喜欢把它放在animate()以内,这样会更顺畅。

这是我对您的 Fiddle 所做的唯一更改:

$('.collapse').on('shown.bs.collapse', function() {
    if (location.hash) {
        $(location.hash).show();
    }

    var thisId = $(this).attr("id");
    var thisOffsetTop = $("#" + thisId).offset().top;
    var headerHeight = $(".navbar").height();
    var myTitleHeight = $(".container h1").first().height();

    console.log(thisId);
    console.log("thisOffsetTop: " + thisOffsetTop);
    console.log("headerHeight: " + headerHeight);
    console.log("MyTitleHeight: " + myTitleHeight);

    // Animation to scrollTo the right position
    $('html, body').animate({
        scrollTop: thisOffsetTop - headerHeight - myTitleHeight
    });
});

我留下了所有相关的 console.log()...
查看更新后的 Fiddle.

好吧,我坚持了下来,终于找到了解决办法。我唯一做错的是这一行 $(location.hash).show(); 需要改为 location.href = location.hash;.

这使得它跳转以在页面顶部 header 正下方显示所需的 div。

这是updated fiddle

在其中,单击 "More Details" 面板 header,然后单击该面板中的 link(即 "Buried Sub Anchor")。这将展开 "Miscellaneous" 面板 header 并将页面向右跳转到 "Buried Sub Anchor text" div.

一路上我还捡到了一些有价值的东西。如果 above-mentioned 代码更改是我所做的全部(即 $(location.hash).show(); -> location.href = location.hash;),当单击 link 时,它会展开目标面板并跳转到您想要的位置去。但它也会使面板展开/显示您也刚刚离开。

原因对我来说并不明显,并通过以下代码修复:

$('#accordion .panel-collapse').collapse({ 
  parent: '#accordion', 
  toggle: false 
});

我在 this github page 上找到了那个代码。它初始化 individual accordion 折叠元素,因为

the data api...lazy instantiates, something which .collapse('show') doesn't take into account.

所以现在在更新的 fiddle 中,当您单击 link 时,它会关闭离开面板,打开目标面板并将页面直接跳转到目标 div,只是我想要的方式。