Help with Scroll/Follow Sidebar

喜夏-厌秋 提交于 2019-12-04 18:30:15

You just need to add an extra conditional statement that does nothing if $(window).scrollTop() is greater than a certain threshold. The problem lies in setting that threshold as I assume you want it to work on pages of varying heights. Fortunately we can use the offset of the footer and the height of the sidebar to determine this threshold. The following might need some tweaking for your particular situation, but basically:

$(function() {

    var $sidebar   = $("#scroll-menu"),
        $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 = 15;

    $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
            });
        }
    });

});
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!