淡出'滚动到顶部'当你从页面底部100px时按钮

时间:2016-02-19 16:20:03

标签: javascript jquery css

我使用简单的jquery"滚动到顶部"插件我在网上找到了,它运作良好。但是,我希望淡出我的滚动到顶部'当我从页面底部100px离开时按钮。有人可以帮忙吗?这是一个小提琴 - https://jsfiddle.net/p1em9gph/

//Check to see if the window is top if not then display button
$(window).scroll(function(){
    if ($(this).scrollTop() > 100) {
        $('.scrollToTop').fadeIn();
    } else {
        $('.scrollToTop').fadeOut();
    }
});

//Click event to scroll to top
$('.scrollToTop').click(function(){
    $('html, body').animate({scrollTop : 0},800);
    return false;
});
<a href="#" class="scrollToTop">Scroll To Top</a>

1 个答案:

答案 0 :(得分:2)

您需要修改逻辑,将scrollTop()比较为文档的高度,减去窗口的高度,减去100px的距离。试试这个:

//Check to see if the window is top if not then display button
$(window).scroll(function() {
    if ($(this).scrollTop() > $(document).height() - $(window).height() - 100) {
        $('.scrollToTop').fadeIn();
    } else {
        $('.scrollToTop').fadeOut();
    }
});

Working example

更新

从下面的评论中可以看出,当滚动从顶部或底部滚动100px时,你只想显示div,在这种情况下试试这个:

$(window).scroll(function() {
    if ($(this).scrollTop() < 100 || $(this).scrollTop() > $(document).height() - $(window).height() - 100) {
        $('.scrollToTop').fadeOut();
    } else {
        $('.scrollToTop').fadeIn();
    }
});

Working example

相关问题