0

客户要求将某些模板上的侧边栏设置为粘性。然而,问题是有问题的侧边栏有时会太高而无法容纳在浏览器窗口中。

我们的想法是,当侧边栏超出可视区域时,它会正常滚动,但只要底部可见,它就会停止。当用户向上滚动时,它将再次启动。

我似乎找不到任何发生这种情况的例子。我的 google-fu 让我失望了。

有人对如何实施有任何想法吗?我想我可以使用一些相当简单的 jQuery,但是很难确定要使用哪些钩子。

任何教程、示例或建议将不胜感激。

4

1 回答 1

0

我会这样处理它:

我假设您的侧边栏容器的 ID 为“侧边栏”

$(document).ready(function() {
    if($('#sidebar').height() < $(window).height()) {
        $('#sidebar').addClass('sticky');
    }
});

然后使用你想要的任何属性创建一个名为 sticky 的 css 类,当它没有屏幕那么高时,例如:

.sticky {
   position:fixed;
   left:0;
   top:0;
}

编辑:position:fixed !important;如果粘性类没有覆盖您在#sidebar 上设置的css,则使用。

再次编辑:对不起,我重新阅读了这个问题。我将从上面开始,然后你会想要绑定到窗口滚动事件并运行一些测试 - 尝试这样的事情:

$(window).bind("scroll", function(){
    if($('#sidebar').offset().top - $("html").scrollTop() < 0) {
        //the top of the sidebar has scrolled above the top of the viewport
    } else {
        //the top of the sidebar is still below the top of the viewport
    }
});

希望这对您有所帮助。

于 2012-07-05T00:46:13.383 回答