粘性侧边栏创建无限滚动

时间:2014-04-09 21:29:15

标签: jquery css sticky

我使用了几乎精确的编码作为http://css-tricks.com/scrollfollow-sidebar/,它没有无限的侧边栏,但是我的。{/ p>

代码:

$(function() {  
    var $sidebar   = $("#left_column"), 
        $window    = $(window),
        offset     = $sidebar.offset(),
        topPadding = 50;
    $window.scroll(function() {
    //console.log($('.view-content').height());
    //@todo, check content height to prevent "infinite scrolling";  this occurs when the sidebar is not fully displayed on the page
        if ($window.scrollTop() > offset.top) {
            $sidebar.stop().animate({
                marginTop: $window.scrollTop() - offset.top + topPadding
            });
        } else {
            $sidebar.stop().animate({
                marginTop: 0
            });
        }
    });    
});

的CSS:

#left_column {
float: left;
top: -10px;
    position: relative;
width: 200px;   

}

但是这段代码在每次接近结尾时都会无限滚动, 它将侧杆推下窗户总高度的30-50% 我做错了什么?

1 个答案:

答案 0 :(得分:1)

我已经遇到了同样的问题,我想我找到了一个可能的解决方案,我会在你的代码示例中展示它:

$(function() {  
var $sidebar   = $("#left_column"), 
    $window    = $(window),
    offset     = $sidebar.offset(),
    topPadding = 50;

$window.scroll(function() {
//console.log($('.view-content').height());
//@todo, check content height to prevent "infinite scrolling";  this occurs when the sidebar is not fully displayed on the page
var  docHeight = $(document).height()-700;
  if($(window).scrollTop() < docHeight) {
    if ($window.scrollTop() > offset.top) {
        $sidebar.stop().animate({
            marginTop: $window.scrollTop() - offset.top + topPadding
        });
    } else {
        $sidebar.stop().animate({
            marginTop: 0
        });
    }
 }
});    
});

你必须添加一个名为docHeight的变量,其中包含documentHeight减去窗口的平均高度(例如700),然后在scroll函数中设置一个新的if子句,以防止在靠近定义的高度级别内滚动文件的底部。

相关问题