Affix div to bottom of window

2019-07-17 02:52发布

I was wondering how I can fix a div to the bottom of the window as it scrolls out of view. I know you can do it with twitter bootstrap but I don't want to use a library.

So far I have some jQuery that I thought would work:

$(window).scroll(function() {
  if (((($('.show_postQuestion').offset().top + 
            $('.show_postQuestion').height()) - 
            ($(window).scrollTop()+$(window).height())) > 0)) {
    // Post form off-screen
    $('.show_postQuestion').addClass('fixed');
  } else {
    $('.show_postQuestion').removeClass('fixed');
  }
});

The .fixed class is just position:fixed; bottom:0;.

The problem with this is that, if the form scrolls off and fixes itself, it is no longer out of view and on the text scroll will un-fix itself, leading it to fix itself again, blah blah blah and making it flicker.

I was wondering if anyone has a suggestion as to how to fix this or an alternative solution?

Thanks!

1条回答
趁早两清
2楼-- · 2019-07-17 03:05

If I understand your question properly, you want to have an element fixed to the bottom of the window if it would usually be further down the page and out of view. And when the user scrolled down to it's natural position it would flow with the scroll as normal.

I modified your function slightly to remember the elements initial position on page load and use that to compare it to the scrollTop position each time.

Fiddle

$(function() {
  var $postQ = $(".show_postQuestion"),
      $postQPos = $postQ.offset().top + $postQ.height(),
      $win = $(window);

  $win.scroll(function() {
    if ($postQPos > $win.scrollTop() + $win.height()) {
      // Post form off-screen
      $('.show_postQuestion').addClass('fixed');
    } else {
      $('.show_postQuestion').removeClass('fixed');
    }
  }).trigger('scroll'); // trigger the event so it moves into position on page load
});
查看更多
登录 后发表回答