首页 文章

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

提问于
浏览
0

我是网络开发人员的新手 . 我花了几天时间研究这个(令人尴尬)并研究了我能想到的一切 .

我正在使用Rails 5,bootstrap 3和jquery 2.1.3 .

我有一个自举手风琴 . 在各种崩溃内容div中,我想要链接到位于同一手风琴但是不同折叠面板的内容 .

在当前的崩溃面板中,我有一个这样的链接:

<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神奇地关闭当前面板并打开目标 . 然后,一旦完成转换,我期待“显示”事件触发,我这样处理:

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

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

总结一下,当我点击我想要的链接时:

  • 当前面板为.collapse('hide')

  • 目标面板为.collapse('show')

  • 要跳转到目标面板中的锚定div的页面

相反,总是:

  • 当前面板没有变化(即保持显示)

  • 目标面板确实显示

  • 页面跳转到新位置,但不在所需的锚点部分附近

我的问题是:

  • 为什么当前的面板没有崩溃?我希望引导手风琴功能能够在 $collapse.collapse('show') 调用的情况下执行此操作 .

  • 为什么页面不滚动到链接的内容?

Here is a fiddle . 重现:

  • 点击"More Details"部分

  • 一直向下滚动

  • 单击"Buried sub anchor"链接

2 回答

  • 0

    你必须强制 scrollTop 这样做 .
    我喜欢在 animate() 内制作它,这使它更顺畅 .

    这是我对你的小提琴的唯一改变:

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

  • 0

    好吧,我坚持下去,最后有一个解决方案 . 唯一我做错的是这条线需要 location.href = location.hash; 而不是 location.href = location.hash; .

    这样就可以跳转到 Headers 下方页面顶部显示所需的div .

    这是updated fiddle .

    在其中,单击“更多详细信息”面板 Headers ,然后单击该面板中的链接(即“Buried Sub Anchor”) . 这将扩展“Miscellaneous”面板 Headers 并将页面右移到“Buried Sub Anchor text”div .

    在旅程中,我选择了其他有 Value 的东西 . 如果上面提到的代码改变是我所做的(即 $(location.hash).show(); - > location.href = location.hash; ),当点击链接时,它会展开目标面板并跳转到你想去的地方 . 但它也会让面板扩大/显示你刚刚离开 .

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

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

    我发现this github page上的代码 . 它初始化了个别的手风琴折叠元素,因为

    数据api ... lazy instantiates,.collapse('show')没有考虑到的东西 .

    因此,现在在更新的小提琴中,当您单击链接时,它会关闭离开面板,打开目标面板并将页面直接跳转到目标div,就像我想要的那样 .

相关问题