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

后端 未结 21 1479
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 08:11

    Here's one more version to try for those having issues with the others. It pulls together the techniques discussed in this duplicate question, and generates the required helper DIVs dynamically so no extra HTML is required.

    CSS:

    .sticky { position:fixed; top:0; }
    

    JQuery:

    function make_sticky(id) {
        var e = $(id);
        var w = $(window);
        $('
    ').insertBefore(id); $('
    ').hide().css('height',e.outerHeight()).insertAfter(id); var n = e.next(); var p = e.prev(); function sticky_relocate() { var window_top = w.scrollTop(); var div_top = p.offset().top; if (window_top > div_top) { e.addClass('sticky'); n.show(); } else { e.removeClass('sticky'); n.hide(); } } w.scroll(sticky_relocate); sticky_relocate(); }

    To make an element sticky, do:

    make_sticky('#sticky-elem-id');
    

    When the element becomes sticky, the code manages the position of the remaining content to keep it from jumping into the gap left by the sticky element. It also returns the sticky element to its original non-sticky position when scrolling back above it.

提交回复
热议问题