Fixed sidebar on the scroll stop at div

2019-06-06 14:10发布

I try to make sure that a div "filter" becomes fixed when scrolling and then stop when it comes down to "outside_footer_wrapper". use the following script but can not get it to work?

jsfiddle

$(function() {
        var top = $('#filter').offset().top - parseFloat($('#filter').css('marginTop').replace(/auto/, 0));
        var footTop = $('#outside_footer_wrapper').offset().top - parseFloat($('#outside_footer_wrapper').css('marginTop').replace(/auto/, 0));

        var maxY = footTop - $('#filter').outerHeight();

        $(window).scroll(function(evt) {
            var y = $(this).scrollTop();
            if (y > top) {
                if (y < maxY) {
                    $('#filter').addClass('fixed').removeAttr('style');
                } else {
                    $('#filter').removeClass('fixed').css({
                        position: 'absolute',
                        top: (maxY - top) + 'px'
                    });
                }
            } else {
                $('#filter').removeClass('fixed');
            }
        });
    });

4条回答
祖国的老花朵
2楼-- · 2019-06-06 14:27

Is it something like this?

jsfiddle

// get box div position
var box = document.getElementById('box').offsetTop;

window.onscroll = function(){

    // get current scroll position
    var scroll_top = document.body.scrollTop || document.documentElement.scrollTop;

    document.getElementById('scbox').innerText = scroll_top + ' ' + box;

    // if current scroll position >= box div position then box position fixed
    if(scroll_top >= box)
        document.getElementById('box').style.position = 'fixed';
    else
        document.getElementById('box').style.position = 'relative';


}
查看更多
萌系小妹纸
3楼-- · 2019-06-06 14:32

try this:

#sidebar {
 position: fixed;
}

jsfiddle here

查看更多
爱情/是我丢掉的垃圾
4楼-- · 2019-06-06 14:33

if you know at which pixel number the filter have to be fixed and at which pixel number the footer starts you can try this function:

scrollTop

查看更多
走好不送
5楼-- · 2019-06-06 14:42

If you want to stop the position:fixed after you reach the footer you can do something like this faking with the top:

$(function() {
    var top = $('#filter').offset().top,
        footTop = $('#outside_footer_wrapper').offset().top,
        maxY = footTop - $('#filter').outerHeight();
    $(window).scroll(function(evt) {
        var y = $(this).scrollTop();
        if (y > top) {
            $('#filter').addClass('fixed').removeAttr('style');
            if (y > maxY-20){
             var min = y - maxY + 20;
            $('#filter').css('top','-'+min+'px');
            }
       } else {
            $('#filter').removeClass('fixed');
        }
    });
});

Also take in care with the CSS for the class fixed you need to make that with equal specificity of #filter I made this change:

#sidebar #filter.fixed /*Add #sidebar*/

Check This Demo Fiddle

查看更多
登录 后发表回答