简体   繁体   English

粘滞侧边栏不会停止滚动

[英]Sticky sidebar doesn't stop scrolling

I have a sticky sidebar on my page using the following script: 我的页面上有一个粘性边栏,使用以下脚本:

$(function() {
            var offset = $("#sidebar").offset();
            var 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
                    });
                };
            });
        });

The problem is that it should stop scrolling when it reaches the Middle Block Div. 问题是它应该在到达Middle Block Div时停止滚动。 At the moment it doesn't stop scrolling and it pushes all the rest of the content down. 目前,它不会停止滚动,而是将所有其他内容推送下来。 Is there a way to fix this? 有没有办法来解决这个问题?

- DEMO - - 演示 -

Thank you. 谢谢。

you have check if Sidebar has been moved to Middle Box, if so just stop the sidebar to animate. 你检查边栏是否已经移动到中间框,如果是这样,只需停止侧边栏动画。 like this : 像这样 :

$(function() {
            var offset = $("#sidebar").offset();
            var boxOffset = $(".middle-block").offset().top;
            var sidebarHeight = parseInt($("#sidebar").outerHeight());
            var topPadding = 15;
            $(window).scroll(function() {
                if ($(window).scrollTop() > offset.top) {
                    if(($(window).scrollTop()+sidebarHeight)<boxOffset){
                    $("#sidebar").stop().animate({
                        marginTop: $(window).scrollTop() - offset.top + topPadding
                    });
                    }
                } else {
                    $("#sidebar").stop().animate({
                        marginTop: 0
                    });
                };
            });
        });

check it live here: jsfiddle 在这里查看: jsfiddle

You need to get the position of .middle-block and stop the sidebar from scrolling at that point (minus the height of the sidebar). 您需要获取.middle-block的位置并停止侧边栏在该点滚动(减去侧边栏的高度)。

Change your jQuery function to: 将您的jQuery函数更改为:

$(function() {
    var offset = $("#sidebar").offset();
    var mbOffset = $(".middle-block").offset();
    var mbPos = mbOffset.top - $("#sidebar").outerHeight() - 30; /*30px extra space*/
    var topPadding = 15;
    $(window).scroll(function() {
        if ($(window).scrollTop() > offset.top ) {
            if(  $(window).scrollTop() < mbPos ) {
                $("#sidebar").stop().animate({
                    marginTop: $(window).scrollTop() - offset.top + topPadding
                });
            }
        } else {
            $("#sidebar").stop().animate({
                marginTop: 0
            });
        };
    });
});

Updated Pen 更新了笔

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM