Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

html - jQuery: Hide/Show Divs on page scroll

jsfiddle: http://jsfiddle.net/MFUw3/5/

jQuery:

function showDiv() {
    if ($(window).scrollTop() > 610) {
        $(".a").css({"position": "fixed", "top": "10px"});
    } else {
        $(".a").css({"position": "relative", "top": "0px"});
    }
}
$(window).scroll(showDiv);
showDiv();

HTML:

<div>
    <div class="a">
        A
    </div>
    <div class="b">
        B
    </div>
</div>

I want to make it so when the user has scrolled past div "B" (A and B are out of sight), then div "A" will fade in and fix itself to the top of the browser.

When you scroll up and div "B" is back in sight, I want div "A" to fade out and reposition itself back to where it was originally.

My code currently does just this, EXCEPT it doesn't do fading.

I've tried messing around with .is(":visible"), .is(":hidden"), .hide(); so that I can use fadeIn(); and fadeOut();, but no matter what I try, I can't figure it out, and I know this isn't efficient in the first place. There's probably some way to detect if it's passed a div instead of passed a certain coordinate?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Here's something that should suit your needs:

function showDiv() {
    if ($(window).scrollTop() > 610 && $('.a').data('positioned') == 'false') {
        $(".a").hide().css({"position": "fixed", "top": "10px"}).fadeIn().data('positioned', 'true');
    } else if ($(window).scrollTop() <= 610 && $('.a').data('positioned') == 'true') {
        $(".a").fadeOut(function() {
            $(this).css({"position": "relative", "top": "0px"}).show();
        }).data('positioned', 'false');
    }
}
$(window).scroll(showDiv);
$('.a').data('positioned', 'false');

And the link to the working example: http://jsfiddle.net/MFUw3/10/

Edit: I have added the code improvements suggested by Sparky672 and the (initially omitted) fadeout.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...