How to get dynamic data-offset values for Bootstra

2019-01-17 20:00发布

I would like to use the Affix method described in Bootstraps documentation (http://getbootstrap.com/javascript/#affix), however the navbar I would like to fix to the top of the page after it scrolls to it can have different offset values depending upon the content above it.

Here's an example of the navbar:

<div class="navbar navbar-default" data-spy="affix" data-offset-top="200">
  <ul class="nav navbar-nav">
    <li class="active"><a href="#">Link</a></li>
    <li><a href="#">Link 1</a></li>
    <li><a href="#">Link 2</a></li>
  </ul>
</div>

As you can see, the data-offset-top is currently set at 200. This works fine if the content above is 200px tall, but the content above is dynamic and so the height above this navbar isn't always the same. How can I make the vale for data-offset-top be dynamic?

I'm guessing I'll have to use the javascript way of doing it but I'm nit sure.

7条回答
爷的心禁止访问
2楼-- · 2019-01-17 20:26

I was having a lot of trouble with this earlier, and for some reason I couldn't get any of the solutions other people had suggested to work. I'm relatively new to Bootstrap and JQuery, so I was probably doing something wonky I wasn't catching. Regardless, I found a solution that works really well, although it doesn't strictly speaking use the affix functionality as Bootstrap intends. I kept my #thisElement.affix {top: desiredFixedPosition;} CSS intact, but got rid of the data-spy and data-offset-top attributes from #thisElement's HTML tag. I then hard-coded this in JQuery:

var newAffix = function() {
    if($("otherElementsAboveThisElement").height() <= $(window).scrollTop()) {
        $("#thisElement").addClass("affix");
    } else {
        $("#thisElement").removeClass("affix");
    }
}

$(document).ready(function() {
    $(window).resize(newAffix);
    $(window).scroll(newAffix);
}

As far as I've tested, this works regardless of how much you resize the page or scroll, and if you get creative with how you call it in the $(document).ready() function you could even have the menu remain in the right position during height animations. As stated, this isn't technically a fully "Bootstrap approved" solution, but it integrates well enough into a Bootstrap site that it should work for some :)

查看更多
登录 后发表回答