3

我已经制作了一个带有 div 的 div,我希望内部 div 在外部 div 内上下滚动页面上上下浮动。我以某种方式设法使其限制不超出外部 div 表单,但是当它到达底部时,它会下降到页面底部。请帮助我,这是我的代码 css

CSS

#comment {
  position: absolute;
  /* just used to show how to include the margin in the effect */
}

HTML

<!--the outer div in which i have whole content -->
<div class="content">
    <!--the floating div, remains well inside form top but moves down outside div from bottom -->
    <div class="ftwrapper" id="comment">            
    </div><!--fb/twitter ends-->
</div>

jQuery

    $(function () {
        var msie6 = $.browser == 'msie' && $.browser.version < 7;
        if (!msie6) {
            var top = $('#comment').offset().top - parseFloat($('#comment').css('margin-top').replace(/auto/, 0));
            $(window).scroll(function (event) {
                // what the y position of the scroll is
                var y = $(this).scrollTop();

                // whether that's below the form
                if (y >= top) {
                    // if so, ad the fixed class
                    $('#comment').addClass('fixed');
                } else {
                    // otherwise remove it
                    $('#comment').removeClass('fixed');
                }
            });
        }  
    });
4

1 回答 1

1

我根据您的要求做了一个样本测试。如果滚动太快,它就不能很好地工作,否则就可以了。稍后我会对其进行一些更改。

var prevScroll = 0;
$(window).unbind("scroll");
function reposition() {
    var contPos  = $("#container").offset();
    var comment = $('#comment');    
    contPos.bottom = contPos.top + $("#container").outerHeight();
    console.log('contPos',contPos);
    $(window).scroll(function (event) {
        // what the y position of the scroll is
        var     scroll = $(window).scrollTop()
            ,   y = scroll
            ,   pos = comment.offset()
        ;
        pos.bottom = comment.outerHeight();
        if ( scroll > prevScroll) {
            //down
        } else {
            //up
        }
        prevScroll = scroll;
        // whether that's below the form
        console.log(pos.bottom + scroll ,":", contPos.bottom);
        if (contPos.top > scroll) {
            // if so, ad the fixed class
            comment.css({
                position: 'relative',
                bottom  : '0px',
                left    : '0px'
            });
            console.log("Too High");
        } else if ( pos.bottom + scroll > contPos.bottom) {
            //comment.removeClass('fixed');
            comment.css({
                position: 'absolute',
                top      : (contPos.bottom - comment.outerHeight() )+'px',
                left     : pos.left+'px'
            });

            console.log("Too Low");
        } else {
            // middle area
            console.log("Perfect");
            comment.css({
                position: 'fixed',
                top   : '0px',
                left  : pos.left + 'px'
            });
        }
    });
}
$(document).ready(reposition);

Jsfiddle 测试

于 2013-11-03T19:05:39.097 回答