Show/hide div on window scroll

2019-07-26 17:05发布

I have a div element #btns that is hidden by default. It should be displayed on scrolling 200px from top and again hidden after 500px from top.

Here is my (non-working) code:

$(window).scroll(function() {
    if ($(this).scrollTop()>200) {
        $('#btns').fadeIn();
    } 
    elseif ($(this).scrollTop()<500) {
        $('#btns').fadeIn();
    } else {
        $('#btns').fadeOut();
    }
});

1条回答
做自己的国王
2楼-- · 2019-07-26 18:04

You can add a class hide in button like this:

$(function() {
    $(window).scroll(function() {
        console.log('scrolling ', $(window).scrollTop(), $(document).height());
        if($(window).scrollTop() >= 200 && $(window).scrollTop() <= ($(document).height() - 500)) {
            $('#btns').removeClass('hide');
        } else {
            $('#btns').addClass('hide');
        }
    });
});

DEMO https://jsfiddle.net/1ks8at6r/5/

查看更多
登录 后发表回答