如何停止在指定的点使用jQuery的浮动div

如何停止在指定的点使用jQuery的浮动div

问题描述:

我想停止浮动(滑动)div时,它到达包含div的底部,但它不工作。变量bottom是包含div的页面上的最低点,但出于某种原因不应如其所愿。任何人都有更好的方法?如何停止在指定的点使用jQuery的浮动div

$(document).ready(function() { 

    var top = $('#buttonsDiv').offset().top - parseFloat($('#buttonsDiv').css('margin-top').replace(/auto/, 0)); 
    var bottom = $('#mainBody').offset().top + $('#mainBody').height(); 

    $(window).scroll(function (event) { 

     // what the y position of the scroll is 
     var y = $(this).scrollTop(); 
     var z = y + $('#buttonsDiv').height(); 

     // whether that's below the form 
     if (y >= top && z <= bottom) { 
      // if so, add the fixed class 
      $('#buttonsDiv').addClass('fixed'); 
     } else { 
      // otherwise remove it 
      $('#buttonsDiv').removeClass('fixed'); 
     } 
    }); 
}); 
+0

在你的'.fixed'类中,你给了'bottom:0;'? – techfoobar 2011-12-20 16:53:56

+0

我试着添加它,它仍然没有工作。问题是找到一种方法让scroll函数识别浮动元素的底部。我想我已经在上面的代码中解决了这个问题,但是让它在包含它的div底部停下来让我感到困惑。 – user1108210 2011-12-20 18:33:10

+1

你可以包括你的HTML和CSS和/或一个工作的例子吗? – 2011-12-20 22:04:11

尝试以下条件:

if (y >= top && z <= bottom) { 
    // if so, add the fixed class 
    $('#buttonsDiv').addClass('fixed'); 
} else if(z > bottom) { 
    // otherwise remove it 
    $('#buttonsDiv').removeClass('fixed').addClass('absolute'); 
} else { 
    // otherwise remove it 
    $('#buttonsDiv').removeClass('fixed'); 
} 

一旦你滚过容器DIV(#mainBody),浮动DIV(#buttonsDiv)应定位 '绝对' 到容器的底部DIV。

在这种情况下,只需用浮动div或padding-bottom与外部div定义margin-bottom应该会有所帮助。我在以下网站中使用了类似的东西:www.emotionstorm.com,以停止顶部横幅下方的购物车。 如果您需要类似代码的帮助,请让我知道。