Sticking Div to Top After Scrolling Past it

前端 未结 1 1576
耶瑟儿~
耶瑟儿~ 2020-12-16 01:17

Right now, I\'m able to stick the div to the top after it scrolls down 320px but I wanted to know if there is another way of achieving this. Below

相关标签:
1条回答
  • 2020-12-16 01:51

    Try using the offset().top of the #navwrap element. That way the element will be fixed from it's starting position in the document, regardless of where that is. For example:

    function fixDiv() {
        var $div = $("#navwrap");
        if ($(window).scrollTop() > $div.data("top")) { 
            $div.css({'position': 'fixed', 'top': '0', 'width': '100%'}); 
        }
        else {
            $div.css({'position': 'static', 'top': 'auto', 'width': '100%'});
        }
    }
    
    $("#navwrap").data("top", $("#navwrap").offset().top); // set original position on load
    $(window).scroll(fixDiv);
    

    Example fiddle

    0 讨论(0)
提交回复
热议问题