Bootstrap 3.0 scrollspy responsive offsets

前端 未结 3 1457
我寻月下人不归
我寻月下人不归 2020-12-31 16:19

I\'m trying to get Bootstrap\'s scrollspy to work reliably on a responsive site on which the top navbar\'s height changes according to the width of the media/browser. So ins

3条回答
  •  春和景丽
    2020-12-31 16:52

    Scrollspy set a list of targets / offset after initialization. If you resize your screen scrollspy is not initialized again. You will have reload your page to recalculate the offsets.

    The "accumulating" offset in effect you mention is cause by the same list of offsets with different content heights.

    To could also trigger this reload with $(window).resize() note some browser will fire this twice, see https://stackoverflow.com/a/4298653/1596547 for a solution:

    var id; 
    
    $(window).resize(function() 
    {
        clearTimeout(id);
        id = setTimeout($('body').scrollspy({ target: '' }), 500);
    });
    

    Note the docs on http://getbootstrap.com/javascript/#scrollspy tell you something similar:

    "When using scrollspy in conjunction with adding or removing of elements from the DOM, you'll need to call the refresh method "

    With the above, you will get something like:

    var id; 
    
    $(window).resize(function() 
    {
        clearTimeout(id);
        id = setTimeout($('[data-spy="scroll"]').each(function () {var $spy = $(this).scrollspy('refresh'}), 500);
    });
    

    NOTE: The scollspy plugin uses jQuery's scrollTop() function for calculations. So also read this: http://blog.jonathanargentiero.com/?p=134.

提交回复
热议问题