简体   繁体   中英

Bootstrap 3 affix position after page refresh

I have configured an affix that mostly works, as can be seen on this page: http://wisderm.com/ingredients/Green+Tea+Extract

This is my code for dynamically changing the affix offsets:

// nav-pills is the class of the <ul> element of the sidebar
// #hero-unit is the jumbotron

// where to start scrolling from
$('.nav-pills').affix( {
    offset: { top: function() { return $('#hero-unit').outerHeight(true)+10; } }
});

// after changing from affix-top to affix
$('.nav-pills').on('affixed.bs.affix', function() {
    $('.nav-pills').css("margin-top", function() { return -$('#hero-unit').outerHeight(true)+10; } );
});

// after changing back to from affix to affix-top
$('.nav-pills').on('affixed-top.bs.affix', function() {
    $('.nav-pills').css("margin-top", 0);
});

The problem is, once I scroll down to a place where affix-top has been changed to affix and I refresh the page, the affix that loads is a lot lower down the page than it should be. Why is this happening and how can I fix it?

Well, this is an old question, but the answer will help somebody:

Your problem is fixed by adding the event listeners before you initialize the affix .

See thread in Github https://github.com/twbs/bootstrap/pull/14331

try this:

// after changing from affix-top to affix
$('.nav-pills').on('affixed.bs.affix', function() {
    $('.nav-pills').css("margin-top", function() { return -$('#hero-unit').outerHeight(true)+10; } );
});

// after changing back to from affix to affix-top
$('.nav-pills').on('affixed-top.bs.affix', function() {
    $('.nav-pills').css("margin-top", 0);
});
$('.nav-pills').affix( {
    offset: { top: function() { return $('#hero-unit').outerHeight(true)+10; } }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM