Jquery 滚动函数排除可变高度

Jquery scroll function exclude variable height

本文关键字:高度 排除 滚动 函数 Jquery      更新时间:2023-09-26

我有一个响应式网站,所以页脚高度是可变的。

滚动

函数在页面底部触发以扩展内容(无限滚动),但这需要在底部减去页脚高度。

$(window).scroll(function() {
    if ( $(window).scrollTop() == $(document).height() - $(window).height() ) {
        alert('fire!');
    }
});

这段代码适用于底部,我在这里找到的解决方案的问题是 if 语句两次为真,因为运算符是:高于或等于 (>=) 而不是 (==)。所以它被触发两次,超时将无法解决。

$(window).scroll(function() {
    scrollDistance = $(window).scrollTop() + $(window).height();
    footerDistance = $('footer').offset().top;
    if (scrollDistance >= footerDistance) {
        alert('fire!');
    }
})

这是我在这里找到的解决方案,但不是很好,它正在执行双重警报。

我还尝试了以下代码:

$(window).scrollTop() == $(document).height() - $(window).height() - $('footer').height();
$(window).scrollTop() == ($(document).height() - $('footer').height()) - $(window).height();

添加了一个标志 hasEventBeenFired 并在事件被触发后将其设置为 true。要再次触发它,您需要在某些事件上再次使值为 false。

var hasEventBeenFired = false;
$(window).scroll(function() {
    scrollDistance = $(window).scrollTop() + $(window).height();
    footerDistance = $('footer').offset().top;
    if (scrollDistance >= footerDistance && !(hasEventBeenFired)) {
    hasEventBeenFired = true;
        alert('fire!');
    }
})