Bootstrap accordion scroll to top of active panel heading

隐身守侯 提交于 2019-12-03 06:00:12

I used this and it works fine you can adjust the -20 after the .offset().top if you need to tweak it up or down a little.

$(function () {
    $('#accordion').on('shown.bs.collapse', function (e) {
        var offset = $('.panel.panel-default > .panel-collapse.in').offset();
        if(offset) {
            $('html,body').animate({
                scrollTop: $('.panel-title a').offset().top -20
            }, 500); 
        }
    }); 
});

This is to target the specific .panel-heading clicked as per James Wilson's comment on the accepted answer.

$(function () {
    $('#accordion').on('shown.bs.collapse', function (e) {
        var offset = $(this).find('.collapse.in').prev('.panel-heading');
        if(offset) {
            $('html,body').animate({
                scrollTop: $(offset).offset().top -20
            }, 500); 
        }
    }); 
});

All I changed from gigelsmith's accepted answer is 'var offset' and the scrollTop's target.

I couldn't get the answer above to work, perhaps I'm missing something but I can't see how the scrollTop line above relates to the currently opened accordion item so used the following code instead. Hope it helps someone else:

$(function () {
$('#accordion').on('shown.bs.collapse', function (e) {
    var offset = $('.panel.panel-default > .panel-collapse.in').offset();
    if(offset) {
        $('html,body').animate({
            scrollTop: $('.panel-collapse.in').siblings('.panel-heading').offset().top
        }, 500); 
    }
});
});

Always animate looks a bit too much so this is my version to only do the job when heading is over the visible part. (note that I use a data-accordion-focus to apply the fix)

$('[data-accordion-focus]').on('shown.bs.collapse', function (e) {
    var headingTop = $(e.target).prev('.panel-heading').offset().top - 5;
    var visibleTop = $(window).scrollTop();
    if (headingTop < visibleTop) {
        $('html,body').animate({
            scrollTop: headingTop
        }, 500);
    }
});

By using .panel-default as selector of .on(), you can scroll to the active panel.

$('#accordion').on('shown.bs.collapse', '.panel-default', function (e) {
    $('html,body').animate({
        scrollTop: $(this).offset().top
    }, 500); 
}); 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!