How to use the new affix plugin in twitter's bootstrap 2.1.0?

后端 未结 9 1608
梦谈多话
梦谈多话 2020-11-29 15:17

The bootstrap documentation on that topic is a little confusing to me. I want to achieve similar behaviour like in the docs with the affix navbar: The navbar is below a para

9条回答
  •  孤独总比滥情好
    2020-11-29 15:23

    I was having a similar problem, and I believe I found an improved solution.

    Don't bother specifying data-offset-top in your HTML. Instead, specify it when you call .affix():

    $('#nav').affix({
        offset: { top: $('#nav').offset().top }
    });​
    

    The advantage here is that you can change the layout of your site without needing to update the data-offset-top attribute. Since this uses the actual computed position of the element, it also prevents inconsistencies with browsers that render the element at a slightly different position.


    You will still need to clamp the element to the top with CSS. Furthermore, I had to set width: 100% on the nav element since .nav elements with position: fixed misbehave for some reason:

    #nav.affix {
        position: fixed;
        top: 0px;
        width: 100%;
    }
    

    One last thing: When an affixed element becomes fixed, its element no longer takes up space on the page, resulting in the elements below it to "jump". To prevent this ugliness, I wrap the navbar in a div whose height I set to be equal to the navbar at runtime:

    
    

    .

    $('#nav-wrapper').height($("#nav").height());
    

    Here's the obligatory jsFiddle to see it in action.

提交回复
热议问题