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

后端 未结 21 1730
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:45

    This is how i did it with jquery. This was all cobbled together from various answers on stack overflow. This solution caches the selectors for faster performance and also solves the "jumping" issue when the sticky div becomes sticky.

    Check it out on jsfiddle: http://jsfiddle.net/HQS8s/

    CSS:

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

    JS:

    $(document).ready(function() {
        // Cache selectors for faster performance.
        var $window = $(window),
            $mainMenuBar = $('#mainMenuBar'),
            $mainMenuBarAnchor = $('#mainMenuBarAnchor');
    
        // Run this on scroll events.
        $window.scroll(function() {
            var window_top = $window.scrollTop();
            var div_top = $mainMenuBarAnchor.offset().top;
            if (window_top > div_top) {
                // Make the div sticky.
                $mainMenuBar.addClass('stick');
                $mainMenuBarAnchor.height($mainMenuBar.height());
            }
            else {
                // Unstick the div.
                $mainMenuBar.removeClass('stick');
                $mainMenuBarAnchor.height(0);
            }
        });
    });
    

提交回复
热议问题