Help with Scroll/Follow Sidebar

試著忘記壹切 提交于 2020-01-13 07:07:30

问题


used the jquery technique to have a scrolling/following sidebar from css-tricks.com, here is the code if you dont know what im talking about:

$(function() {

        var $sidebar   = $("#scroll-menu"),
            $window    = $(window),
            offset     = $sidebar.offset(),
            topPadding = 15;

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

    });

also here is the link http://css-tricks.com/scrollfollow-sidebar/

The only problem that i have with this is that it has an container but when you scroll far enough into footer the sidebar scrolls out of container. Is there a way i can constrain how far it scrolls down?

Here is an image of what is happening: http://tinypic.com/r/2mcj2mv/7

Thanks in advance


回答1:


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

});


来源:https://stackoverflow.com/questions/4716795/help-with-scroll-follow-sidebar

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