在页面滚动结束后检测连续滚动

时间:2020-02-24 03:47:09

标签: javascript html scroll lazy-loading

我正在尝试检测页面底部的持续滚动。

在页面末尾到达页面时,页面会显示更多信息,但当人们在页面末尾滚动更多时,我想显示出来。

我可以检测到滚动的结束,但是我想检测是否有人继续滚动。

<!-- language: lang-js -->
function scrolling() {
    let scrollView = document.getElementById('field-scroll');
    if ($(scrollView).scrollTop() + $(scrollView).innerHeight() >= $(scrollView)[0].scrollHeight) {
        alert('end of the bottom. but I want to show it when doing more scroll not immediately');
    }
}

<div id='field-scroll' onscroll='scrolling()'>
   ...
</div>

谢谢您的帮助。

2 个答案:

答案 0 :(得分:2)

您可以添加一个变量以指示滚动的第一次结束,然后检查该变量以了解用户是否继续滚动。

function scrolling()
{
    let scrollView = document.getElementById('field-scroll');

    if($(scrollView).scrollTop() + $(scrollView).innerHeight()>=$(scrollView)[0].scrollHeight)
    {
        // first end of scroll
        window.endOfScroll = true;
    } else {
        // unset the variable
        window.endOfScroll = null;
    }
}

此外,您需要侦听滚动事件。将这些添加到scrolling函数之外。

const scrollView = document.getElementById('field-scroll');

// mouse wheel
scrollView.addEventListener("wheel", event => {
    const direction = Math.sign(event.deltaY);
    // if user is scrolling down at end of scroll
    if (direction === 1 && window.endOfScroll) {
        showMore();
    }
});

// down arrow
scrollView.addEventListener("keydown", event => {
    // if user is pressing down arrow at end of scroll
    // 40 is the keycode for down arrow
    if (event.keyCode === 40 && window.endOfScroll) {
        showMore();
    }
});

答案 1 :(得分:0)

在窗口上显示.scroll()事件,如下所示:

    $(window).scroll(function() {
   if($(window).scrollTop() + $(window).height() == $(document).height()) {
       alert("bottom!");
   }
});

Behzad fartash