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

后端 未结 21 1834
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条回答
  •  闹比i
    闹比i (楼主)
    2020-11-22 08:08

    You've seen this example on Google Code's issue page and (only recently) on Stack Overflow's edit page.

    CMS's answer doesn't revert the positioning when you scroll back up. Here's the shamelessly stolen code from Stack Overflow:

    function moveScroller() {
        var $anchor = $("#scroller-anchor");
        var $scroller = $('#scroller');
    
        var move = function() {
            var st = $(window).scrollTop();
            var ot = $anchor.offset().top;
            if(st > ot) {
                $scroller.css({
                    position: "fixed",
                    top: "0px"
                });
            } else {
                $scroller.css({
                    position: "relative",
                    top: ""
                });
            }
        };
        $(window).scroll(move);
        move();
    }
    
    
    
     
    

    And a simple live demo.

    A nascent, script-free alternative is position: sticky, which is supported in Chrome, Firefox, and Safari. See the article on HTML5Rocks and demo, and Mozilla docs.

提交回复
热议问题