简体   繁体   English

滚动过去后将Div停留在顶部

[英]Sticking Div to Top After Scrolling Past it

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. 现在,在div向下滚动320px后,我可以将div放在顶部,但是我想知道是否还有另一种方法可以实现此目的。 Below I have my code: 下面有我的代码:

jQuery(function($) {
    function fixDiv() {
        if ($(window).scrollTop() > 320) { 
            $('#navwrap').css({ 'position': 'fixed', 'top': '0', 'width': '100%' }); 
        }
        else {
            $('#navwrap').css({ 'position': 'static', 'top': 'auto', 'width': '100%' });
        }
    }
    $(window).scroll(fixDiv);
    fix5iv();
});

it works, but some divs above it will not always be the same height so I can't rely on the 320px . 它可以工作,但上方的某些divs高度不一定总是相同的,因此我不能依靠320px How do I get this to work without using if ($(window).scrollTop() > 320) so I can get it to fade in at the top after the user scrolls past the div #navwrap ? 如何在不使用if ($(window).scrollTop() > 320)情况下使其工作,以便在用户滚动经过div #navwrap之后可以使其淡入顶部?

Try using the offset().top of the #navwrap element. 尝试使用#navwrap元素的offset().top 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 小提琴的例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM