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

use*_*210 6 html javascript jquery

我试图阻止浮动(滑动)div到达包含div的底部,但它不起作用.变量bottom是包含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');
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

小智 1

尝试以下条件:

 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');
 }
Run Code Online (Sandbox Code Playgroud)

滚动经过容器 DIV (#mainBody) 后,浮动 DIV (#buttonsDiv) 应“绝对”定位到容器 DIV 的底部。