开发者

Opacity based on scroll position

The following code, will make the "Go to top" button fade in when the scrollTop() is over 400px, that works fine, but i haven't found a way to make it fade out when i go back to the top.

$("#gototop").css("opacity", "0");
$(window).bind('scroll', function(){
    if($(this).scrollTop() > 400) {
        $("#gototop").animate({
            opacity: 100,
        }, 3400);
    }
});

An else after the if didn't help, i tried different options with my non-ninja skills but none worked. Any ideas on how to make it fade out when the scroll is back at the top?

开发者_如何学Go

Thanks.


Something along the lines of either an additional scroll handler that does the opposite or another if inside your first handler should do it (you want to test if scrollTop() < 400.

$(window).bind('scroll', function(){
    if($(this).scrollTop() < 400) {
        $("#gototop").animate({
            opacity: 0,
        }, 3400);
    }
});

Note though, that this is animating it on every call to the scroll event, you probably only want to do it once (when the scroll passes the 400px threshold) so maybe add a variable to record the current state of #gototop.

if(visible && $(this).scrollTop() < 400) {
    visible = !visible;
    //animate
}


I ended up using a plugin called waypoints to handle the scroll position.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜