【问题标题】:Scroll event JQuery - Detecting bottom page滚动事件 JQuery - 检测底部页面
【发布时间】:2021-08-21 00:10:03
【问题描述】:

我正在尝试制作一个无限滚动页面。该脚本在我的计算机(Chrome)上运行良好,但在我朋友的计算机(Chrome 也是)上运行良好。当底部的内容通过ajax附加时,我看到它在检测页面底部时确实有效。

我还看到,一旦我更改页面的宽度(只需移动 chrome 的控制台窗口),加载内容就会起作用。

我猜这是因为 js 没有考虑到 DOM。

有什么想法吗?

start += limit;
var deviceAgent = navigator.userAgent.toLowerCase();
var agentID = deviceAgent.match(/(iphone|ipod|ipad)/);

$(document).bind("scroll", function() {
       
        if(($(window).scrollTop() + $(window).height()) == $(document).height() || agentID && ($(window).scrollTop() + $(window).height()) + 200 > $(document).height()) {
            load($("#search").val(), start, limit)
            start += limit;
            console.log("End of page detected")
        }
    });

function load(search, start=0, limit=20) {

  $("#loader_active").show()

  let form_data = new FormData();
  form_data.append('search', search);
  form_data.append('start', start);
  form_data.append('limit', limit);


  $.ajax({

    url: "http://website.com/ajax/videos.php",
    contentType: false,
    dataType: "json",
    processData: false,
    cache: false,
    data: form_data,
    type: 'POST',

    success: function (data) {
      $(data).each(function(index, value) {
        showVideo(value) // show video creates divs with jquery     containing the data from the json received by the ajax call
      })
      $("#loader_active").hide()

    }
  })
}

【问题讨论】:

  • 您的if 条件似乎是A || B && CC。意图是(A || B) && C 还是A || (B && C)?您可以尝试调试该条件及其值。见Which Logic Operator Takes Precedence
  • 对应A || (B && C),但这不是问题的根源。只是尝试使用 A 会导致同样的问题。我几乎可以肯定它来自 DOM,并且在使用 ajax 添加内容后,滚动事件无法计算滚动条的新高度。但我不知道如何解决它。
  • 看起来像 $(document).height() 这样的值在每次滚动事件触发时都会被评估,因此它们应该反映动态内容。是否可以建立一个working demo 来帮助重现该问题?也许您可以使用 reqres.in 之类的东西通过 AJAX 生成示例数据。如需参考,另请参阅Check if a user has scrolled to the bottom

标签: javascript jquery dom scroll


【解决方案1】:

问题是由相等条件引起的:

$(window).scrollTop() + $(window).height()) == $(document).height() || agentID && ($(window).scrollTop() + $(window).height()) + 200 > $(document).height())

这可以简单地修复

$(window).scrollTop() + $(window).height()) > $(document).height() - 100 ) || ( agentID  && ($(window).scrollTop() + $(window).height()) + 200 > $(document).height())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-03
    • 2011-05-14
    • 2010-12-25
    • 1970-01-01
    • 2011-04-30
    • 2012-03-30
    • 1970-01-01
    相关资源
    最近更新 更多