2

我有一个内容块:

<div id="content_holder">
  <div id="fixed_content"></div>
  <div id="bottom_content"></div>
</div>

我想实现这一点 - 当我用鼠标向下滚动时,该fixed_content块将转动固定位置并粘在页面顶部,直到我向下滚动到bottom_content.

到目前为止,我得到了这个:

var top_positio_saver = $('#fixed_content').offset().top;
$(document).on('scroll', function() {
  if ($('#fixed_content').offset().top < $(document).scrollTop()) {
    $('#fixed_content').css('position', 'fixed');
    $('#fixed_content').css('top', 0);
  }
  if ($(document).scrollTop() < top_positio_saver) {
    $('#fixed_content').css('position', 'static');
    $('#fixed_content').css('top', 0);
    $('#fixed_content').css('margin-top', 0);
  }
});

使用此代码,fixed_content一旦我向下滚动足够多,该块就固定了,一旦向上滚动足够多,该块就会变回静态。这里的问题是,如果我向下滚动太多,这个块会在块的顶部bottom_content,而不是我希望它停在 bottom_content 块附近。

有什么建议么?

4

1 回答 1

0

尝试使用底部块offset.top()和当前文档之间的距离scrollTop()

以下代码应该可以工作。请注意,您可以使用相同的.css()调用设置多个设置。另请注意,第二个if条件是多余的,可以用一个else条件替换。

逻辑是,如果scrollTop已经达到 550px,但底部内容从 500px 开始,则#fixed_content元素将从top: -50px. 这样我们就可以防止溢出。

var top_positio_saver = $('#fixed_content').offset().top;
$(document).on('scroll', function() {

  if (top_positio_saver <= $(document).scrollTop()) {
    var distance = $('#bottom_content').offset().top - $(document).scrollTop();
    var newTop = Math.min(0, distance);

    $('#fixed_content').css({
                                'position': 'fixed',
                                'top': newTop
                            });
  }
  else {
    $('#fixed_content').css({
                                'position': 'static',
                                'top': 0,
                                'margin-top': 0
                            });
  }
});
于 2013-09-09T05:54:28.773 回答