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

后端 未结 21 1702
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:46

    Here is an extended version to Josh Lee's answer. If you want the div to be on sidebar to the right, and float within a range (i.e., you need to specify top and bottom anchor positions). It also fixes a bug when you view this on mobile devices (you need to check left scroll position otherwise the div will move off screen).

    function moveScroller() {
        var move = function() {
            var st = $(window).scrollTop();
            var sl = $(window).scrollLeft();
            var ot = $("#scroller-anchor-top").offset().top;
            var ol = $("#scroller-anchor-top").offset().left;
            var bt = $("#scroller-anchor-bottom").offset().top;
            var s = $("#scroller");
            if(st > ot) {
                if (st < bt - 280) //280px is the approx. height for the sticky div
                {
                    s.css({
                        position: "fixed",
                        top: "0px",
                        left: ol-sl
                    }); 
                }
                else
                {
                    s.css({
                        position: "fixed",
                        top: bt-st-280,
                        left: ol-sl
                    }); 
                }
            } else {
                s.css({
                    position: "relative",
                    top: "",
                    left: ""
                });
    
            }
        };
        $(window).scroll(move);
        move();
    }
    

提交回复
热议问题