fixed div on bottom of page that stops in given place

前端 未结 3 1971
悲哀的现实
悲哀的现实 2020-12-06 19:02

I have fixed div on bottom of my page that works well. I wonder if there is some simple way to make it \"stop\" on some place in page when user srolls down to it. I want it

3条回答
  •  一个人的身影
    2020-12-06 19:46

    I tried setting something up on jsfiddle. While I was writing it up, I see that others have posted their alternatives. In case mine helps in any way: http://jsfiddle.net/PnUmM/1/

    I set the position to relative in the CSS, calculate where it is on document load to keep the info aside and then set it to fixed.

    var sticky_offset;
    $(document).ready(function() {
    
        var original_position_offset = $('#sticky_for_a_while').offset();
        sticky_offset = original_position_offset.top;
        $('#sticky_for_a_while').css('position', 'fixed');
    
    
    });
    
    $(window).scroll(function () {
        var sticky_height = $('#sticky_for_a_while').outerHeight();
        var where_scroll = $(window).scrollTop();
        var window_height = $(window).height();
    
    
        if((where_scroll + window_height) > sticky_offset) {
            $('#sticky_for_a_while').css('position', 'relative');
        }
    
        if((where_scroll + window_height) < (sticky_offset + sticky_height))  {
            $('#sticky_for_a_while').css('position', 'fixed');
        }
    
    });
    

提交回复
热议问题