How can I make a div stick to the top of the screen once it's been scrolled to?

后端 未结 21 1480
Happy的楠姐
Happy的楠姐 2020-11-22 07:12

I would like to create a div, that is situated beneath a block of content but that once the page has been scrolled enough to contact its top boundary, becomes fixed in place

21条回答
  •  花落未央
    2020-11-22 07:54

    Here is another option:

    JAVASCRIPT

    var initTopPosition= $('#myElementToStick').offset().top;   
    $(window).scroll(function(){
        if($(window).scrollTop() > initTopPosition)
            $('#myElementToStick').css({'position':'fixed','top':'0px'});
        else
            $('#myElementToStick').css({'position':'absolute','top':initTopPosition+'px'});
    });
    

    Your #myElementToStick should start with position:absolute CSS property.

提交回复
热议问题