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

后端 未结 21 1717
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:57

    My solution is a little verbose, but it handles variable positioning from the left edge for centered layouts.

    // Ensurs that a element (usually a div) stays on the screen
    //   aElementToStick   = The jQuery selector for the element to keep visible
    global.makeSticky = function (aElementToStick) {
        var $elementToStick = $(aElementToStick);
        var top = $elementToStick.offset().top;
        var origPosition = $elementToStick.css('position');
    
        function positionFloater(a$Win) {
            // Set the original position to allow the browser to adjust the horizontal position
            $elementToStick.css('position', origPosition);
    
            // Test how far down the page is scrolled
            var scrollTop = a$Win.scrollTop();
            // If the page is scrolled passed the top of the element make it stick to the top of the screen
            if (top < scrollTop) {
                // Get the horizontal position
                var left = $elementToStick.offset().left;
                // Set the positioning as fixed to hold it's position
                $elementToStick.css('position', 'fixed');
                // Reuse the horizontal positioning
                $elementToStick.css('left', left);
                // Hold the element at the top of the screen
                $elementToStick.css('top', 0);
            }
        }
    
        // Perform initial positioning
        positionFloater($(window));
    
        // Reposition when the window resizes
        $(window).resize(function (e) {
            positionFloater($(this));
        });
    
        // Reposition when the window scrolls
        $(window).scroll(function (e) {
            positionFloater($(this));
        });
    };
    

提交回复
热议问题