将div附加到窗口底部 [英] Affix div to bottom of window

查看:107
本文介绍了将div附加到窗口底部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何在滚动到视图之外时将div固定到窗口底部。我知道您可以使用twitter引导程序来做到这一点,但我不想使用库。

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.

到目前为止,我有一些我认为可以使用的jQuery:

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');
  }
});

.fixed类只是 position:fixed; bottom:0;

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.

我想知道是否有人建议

谢谢!

推荐答案

如果我正确理解了您的问题,那么您通常希望将其固定在窗口底部,如果该元素通常位于页面的下方并且看不见。然后,当用户向下滚动到自然位置时,滚动将正常流动。

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.

我稍微修改了函数,以记住元素在页面加载和使用时的初始位置每次将其与scrollTop位置进行比较。

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
});

这篇关于将div附加到窗口底部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆