Bootstrap collapse - go to top of the open item?

前端 未结 6 1672
孤街浪徒
孤街浪徒 2021-02-01 07:48

I\'m using the bootstrap collapse function, but when I open an element which has a lot of content, then open the next element, it jumps down and doesn\'t go to the top of the op

6条回答
  •  一整个雨季
    2021-02-01 08:35

    Here is a solution built on others suggestions which:

    • also works for embedded accordians
    • scrolls so the header is also shown
    • only if not already on screen
    • animates as well

    Code:

    $('#accordion').on('shown.bs.collapse', function (e) {
    
      // Validate this panel belongs to this accordian, and not an embedded one
      var actualAccordianId = $('a[href="#' + $(e.target).attr('id') + '"').data('parent');
      var targetAccordianId = '#' + $(this).attr('id');
      if (actualAccordianId !== targetAccordianId) return;
    
      var clickedHeader = $(this).find('.panel > .collapse.in').closest('.panel').find('.panel-heading');
      var offset = clickedHeader.offset();
      var top = $(window).scrollTop();
      if(offset) {
        var topOfHeader = offset.top;
        if(topOfHeader < top) {
          $('html,body').animate({ scrollTop: topOfHeader}, 100, 'swing');
        }
      }
    });
    

提交回复
热议问题