How to fix a header on scroll

后端 未结 12 576
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-27 11:26

I am creating a header that once scrolled to a certain amount of pixels it fixes and stays in place.

Can I do this using just css and html or do i need jquery too?

12条回答
  •  我在风中等你
    2020-11-27 12:07

    The chosen solution did not fit well in my page. So this is a more advanced version that works with bootstrap.

    The javascript

    var stickyOffset = $('.sticky-header').offset().top;
    
    $(window).scroll(function () {
        var sticky = $('.sticky-header'),
            scroll = $(window).scrollTop(),
            header = $('.fixed-header-background');
        sticky.each(function() {
            var left = $(this).offset().left;
            $(this).data('left', left);//I store the left offset
        });
    
        if (scroll >= stickyOffset) {
            sticky.addClass('fixed');
            header.css('display', 'block');
            sticky.each(function() {
                $(this).css('left', $(this).data('left'));//I set the left offset
            });
        } else {
            sticky.removeClass('fixed');
            header.css('display', 'none');
            sticky.each(function () {
                $(this).css('left', '');//I remove the left offset
            });
        }
    });
    

    The CSS

    .fixed-header-background {
        display: none;
         position: fixed;
        top: 50px;
        width: 100%;
        height: 30px;
        background-color: #fff;
        z-index: 5;
        border-bottom-style: solid;
        border-bottom-color: #dedede;
        border-bottom-width: 2px;
    }
    
    .fixed{
         position: fixed;
        top: 52px;
        z-index: 6;
    }
    

    And the HTML

        
    [....]
    My header 1 My header 2

提交回复
热议问题