jQuery: Hide/Show Divs on page scroll

流过昼夜 提交于 2019-11-28 05:56:01

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/8662751/jquery-hide-show-divs-on-page-scroll

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!