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

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...