Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
454 views
in Technique[技术] by (71.8m points)

javascript - 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. 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. 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...