2013-03-04 115 views
2

我想知道如何在窗口底部滚动显示div时将其固定到窗口的底部。我知道你可以用twitter bootstrap来做,但我不想使用库。将div粘贴到窗口的底部

到目前为止,我有一些jQuery的,我认为会的工作:

$(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;

问题是,如果表单滚动并修复自身,它不再出现在视图中,文本滚动将解除其自身,导致它再次修复自己,等等等等等等等等。它闪烁。

我想知道是否有人对如何解决这个问题或其他解决方案有什么建议?

谢谢!

回答

2

如果我正确理解你的问题,你希望有一个元素固定在窗口的底部,如果它通常会进一步向下并离开视图。当用户向下滚动到自然位置时,它将像平常一样流动。

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

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

没错,这 “只是工作”。谢谢! – Raiden616 2013-03-15 11:53:38

+0

@ user1014679很高兴为您效力。 – 2013-03-15 14:56:52