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

后端 未结 21 1790
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:59

    The accepted answer works but doesn't move back to previous position if you scroll above it. It is always stuck to the top after being placed there.

      $(window).scroll(function(e) {
        $el = $('.fixedElement');
        if ($(this).scrollTop() > 42 && $el.css('position') != 'fixed') {
          $('.fixedElement').css( 'position': 'fixed', 'top': '0px');
    
        } else if ($(this).scrollTop() < 42 && $el.css('position') != 'relative') {
          $('.fixedElement').css( 'relative': 'fixed', 'top': '42px');
    //this was just my previous position/formating
        }
      });
    

    jleedev's response whould work, but I wasn't able to get it to work. His example page also didn't work (for me).

提交回复
热议问题