可变高度侧边栏滚动跟随

时间:2012-08-27 19:20:56

标签: jquery scroll sidebar cart

在我正在处理的网站上,我正在使用滚动关注来滚动带有页面的购物车/项目菜单。我正在使用此代码     $(function(){

var $sidebar   = $('.sidebar-scroll'),
    $window    = $(window),
    $footer    = $('.footer'), // use your footer ID here
    offset     = $sidebar.offset(),
    foffset    = $footer.offset(),
    threshold  = foffset.top - $sidebar.height(); // may need to tweak
    topPadding = 200;

$window.scroll(function() {
    if ($window.scrollTop() > threshold) {
        $sidebar.stop().animate({
            marginTop: threshold
        });
    } else if ($window.scrollTop() > offset.top) {
        $sidebar.stop().animate({
            marginTop: $window.scrollTop() - offset.top + topPadding
        });
    } else {
        $sidebar.stop().animate({
            marginTop: 0
        });
    }
});

});

问题是因为我的侧边栏是一个菜单,它的高度可变,具体取决于用户选择添加到购物车的内容。如何修改此代码,以便我的菜单不会超过我的页脚,但仍然可以相应地调整大小。

1 个答案:

答案 0 :(得分:1)

我使用内容作为高度参考而不是页脚来重新编写代码。

工作演示:http://jsfiddle.net/tF8Dj/

var $sidebar   = $('aside'),
    $content   = $('#content');

if ($sidebar.length > 0 && $content.length > 0) {
    var $window    = $(window),
        offset     = $sidebar.offset(),
        timer;

    $window.scroll(function() {
        clearTimeout(timer);
        timer = setTimeout(function() {
            if ($content.height() > $sidebar.height()) {
                var new_margin = $window.scrollTop() - offset.top;
                if ($window.scrollTop() > offset.top && ($sidebar.height()+new_margin) <= $content.height()) {
                    // Following the scroll...
                    $sidebar.stop().animate({ marginTop: new_margin });
                } else if (($sidebar.height()+new_margin) > $content.height()) {
                    // Reached the bottom...
                    $sidebar.stop().animate({ marginTop: $content.height()-$sidebar.height() });
                } else if ($window.scrollTop() <= offset.top) {
                    // Initial position...
                    $sidebar.stop().animate({ marginTop: 0 });
                }
            }
        }, 100); 
    });
}

该示例假定您有侧边栏和内容。计时器是为了表现。

希望它适合你!

编辑: 我还发现了一个带有jquery插件的Tuts+ tutorial,它可以做同样的事情。