Fixed sidebar on the scroll stop at div

2019-06-06 13:56发布

问题:

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

回答1:

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



回答2:

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



回答3:

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';


}


回答4:

try this:

#sidebar {
 position: fixed;
}

jsfiddle here