How to get dynamic data-offset values for Bootstrap 3 affix method

烂漫一生 提交于 2019-11-28 22:32:54

You could use jQuery to get the dynamic content height above the navbar. For example:

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

Working demo: http://bootply.com/69848

In some cases, offset.bottom must also be calculated to determine when to "un-affix" the element. Here's an example of affix-bottom

ThomasReggi

I was absolutely frustrated with the way this works, every time doing some custom calculation and building the offset off the the heights of the elements above the desired affix.

Here's affix at it's best.

The normal boostrap affix doesn't take the items natural offset top position into account, you have to manually pass it in as an attribute. This takes care of that, and accounts for the offset top changing on window resize.

var $attribute = $('[data-smart-affix]');
$attribute.each(function(){
  $(this).affix({
    offset: {
      top: $(this).offset().top,
    }
  })
})
$(window).on("resize", function(){
  $attribute.each(function(){
    $(this).data('bs.affix').options.offset.top = $(this).offset().top
  })
})

I also posted this on code review.

Don't forget to add the data-smart-affix attribute to your affix element

Try this sample code: https://jsfiddle.net/NabiKAZ/qyrauogw/
(In this sample, the height of red section may be 100px or 200px or 300px in diffrence width of window, So need to diffrence data-offset-top when scrolled.)

ThomasReggi's data-smart-affix didn't work for me in some corner cases (when resizing the document, or when the affixed column was too tall). But it gave me a simple idea: Add an empty element before the affixed content, and use that to get the offset. Works well when resized.

While I was at it, I also set the width of the element to be it's natural width in the original parent. Here's my solution:

$('[data-affix-after]').each( function() {
  var elem = $(this);
  var parent_panel = elem.parent();
  var prev = $( elem.data('affix-after') );

  if( prev.length != 1 ) {
    /* Create a new element immediately before. */
    prev = elem.before( '<div></div>' ).prev();
  }

  var resizeFn = function() {
      /* Set the width to it's natural width in the parent. */
      var sideBarNavWidth = parent_panel.width()
          - parseInt(elem.css('paddingLeft'))
          - parseInt(elem.css('paddingRight'))
          - parseInt(elem.css('marginLeft'))
          - parseInt(elem.css('marginRight'))
          - parseInt(elem.css('borderLeftWidth'))
          - parseInt(elem.css('borderRightWidth'));
      elem.css('width', sideBarNavWidth);

      elem.affix({
          offset: {
              top: prev.offset().top + prev.outerHeight(true),
              bottom: $('body>footer').outerHeight(true)
          }
      });
  };

  resizeFn();
  $(window).resize(resizeFn);
});

The HTML that goes with it is:

<div id='before-affix'></div><!-- leave this empty -->
<div data-affix-after='#before-affix'>
    Put content to affix here.
</div>

or

<div data-affix-after='#create'><!-- any ID that doesn't exist -->
    Put content to affix here.
</div>

The required CSS is:

.affix { top: 0px },
.affix-bottom { position: absolute; }

If you want to disable affix (e.g. when the right column is stacked), then use the CSS:

.affix, .affix-bottom { position: static; }

inside the appropriate media query.

GI

I suggest you to add wrapper around affixed div - to avoid the "scroll jump" with affixed navbar. Thomas posted nice solution, but it doesn't include colapsed space after affix and it's not working in 2.x boostrap version which I must use. So i decided to write completly new implementation of affix. It doesn't need boostrap, just jquery. It's my first javascript, so please have mercy :) but maybe it will help somebody. It's always nice to have solution without a bootstrap

function myaffix() {

var affixoffset = $('.navbar').offset().top

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

$(window).scroll(function () {

    if ($(window).scrollTop() <= affixoffset) {
        $('.navbar').removeClass('affix');
    } else {
        $('.navbar').addClass('affix');
    }
});

};

$(document).ready(function () {

   myaffix();

   $(window).on("resize", function () {
       myaffix();
   });

});

You can find example here: http://jsfiddle.net/3ss7fk92/

haui

Skelly above is right and there is no better way to do so. The only possible solution with "native" bootstrap is to attach the affix options with a JavaScript call (as mentioned above in https://stackoverflow.com/a/18702972/2546679).

It is especially not possible to use the data-offset attribute to achieve the same effect (even if this would be much more convenient, and even if the documentation for Affix at http://getbootstrap.com/2.3.2/javascript.html#affix raises hope one could do so).

So one can write

data-offset='{"top":42}'

but one is not allowed to write e.g.:

data-offset='{"top":$("#banner").height()}'

The reason is that the data attributes are parsed through the JQuery .data() API which only allows pure JSON values to be parsed, see https://api.jquery.com/data/.

Thnx ThomasReggi for an idea. But may be more correct to write:

$(this).data('bs.affix').options.offset.top = $(this).offset().top

for those like me who needed a bottom value too that would write analogically.

BTW also I think wrap it in a decorator based on setTimeout (somewhat like debounce).

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 :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!