跟随滚动的侧边栏,但如果比视口高,则滚动自身

Jon*_*ius 28 javascript css jquery

(嘿,来自长期潜伏者的第一篇文章:)

我已经构建了一个简单的侧边栏,可以将" 绝对到固定 "的技巧留在屏幕上,但是想要考虑侧边栏高于视口的帐户场景.

所以我提出了这个想法.一切都从上面开始:

  • 在页面加载时,侧边栏在起始位置绘制,距视口顶部一定距离.
  • 当用户滚动页面时,侧边栏随内容移动
  • 如果侧边栏垂直适合视口,则会固定到顶部

但在这里它变得更有活力:

  • 如果侧边栏比视口高,它会继续滚动内容,直到到达侧边栏的底部,并在那里修复.侧边栏的顶部滚动到视口顶部之外.

  • 当用户向页面顶部滚动时,侧边栏随内容一起移动,直到到达侧边栏的顶部,并在那里修复.侧边栏的底部滚动到视口底部之外.

通过这种方式,侧边栏像往常一样对滚动作出反应,同时在足够近的地方粘贴以查找长页面.

任何指向示例的指针,或jQuery友好的代码片段/指南都将非常感激.

Rya*_*yan 20

我对项目有这个确切的想法,这是一个如何实现它的例子

http://jsfiddle.net/ryanmaxwell/25QaE/


Rob*_*ert 0

像这样的东西可能会起作用。我还没有测试过,但理论上它看起来不错。

$(function(){
    var standardPosition = $('whatYouWantToScroll').offset().top;
    // Cache the standard position of the scrolling element
    $(window).scroll(function() {
        if ($(this).scrollTop() < standardPosition) {
            // if scroll pos is higher than the top of the element
            $('whatYouWantToScroll').css({
                position: 'relative',
                top: '0px'
            });
        } else if ($(window).scrollTop() > $('somethingToReferenceOnTheBottom').offset().top-($('whatYouWantToScroll').height())) {
            // if scroll position is lower than the top offset of the bottom reference
            // + the element that is scrolling height
            $('whatYouWantToScroll').css({
                position: 'absolute',
                top: $('somethingToReferenceOnTheBottom').offset().top-($('whatYouWantToScroll').height())
            });
        } else {
            // otherwise we're somewhere inbetween, fixed scrolling.
            $('whatYouWantToScroll').css({
                position: 'fixed'
            });
        }
    });
});
Run Code Online (Sandbox Code Playgroud)