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

后端 未结 21 1709
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

    I used some of the work above to create this tech. I improved it a bit and thought I would share my work. Hope this helps.

    jsfiddle Code

    function scrollErrorMessageToTop() {
        var flash_error = jQuery('#flash_error');
        var flash_position = flash_error.position();
    
        function lockErrorMessageToTop() {
            var place_holder = jQuery("#place_holder");
            if (jQuery(this).scrollTop() > flash_position.top && flash_error.attr("position") != "fixed") {
                flash_error.css({
                    'position': 'fixed',
                    'top': "0px",
                    "width": flash_error.width(),
                    "z-index": "1"
                });
                place_holder.css("display", "");
            } else {
                flash_error.css('position', '');
                place_holder.css("display", "none");
            }
    
        }
        if (flash_error.length > 0) {
            lockErrorMessageToTop();
    
            jQuery("#flash_error").after(jQuery("
    ")); var place_holder = jQuery("#place_holder"); place_holder.css({ "height": flash_error.height(), "display": "none" }); jQuery(window).scroll(function(e) { lockErrorMessageToTop(); }); } } scrollErrorMessageToTop();​

    This is a little bit more dynamic of a way to do the scroll. It does need some work and I will at some point turn this into a pluging but but this is what I came up with after hour of work.

提交回复
热议问题