当滚动达到 80% 时加载 ajax

Load ajax when scroll reaches 80%

本文关键字:加载 ajax 滚动      更新时间:2023-09-26

我正在使用以下代码,当滚动条到达 botttom 时,它正在工作,

if($(window).scrollTop() == $(document).height() - $(window).height()){

但是,我希望 ajax 在我达到滚动的 70% 而不是 100% 时被触发。

如果当前检查在滚动到页面底部时触发,您可以尝试一些基本的算术:

if ($(window).scrollTop() >= ($(document).height() - $(window).height())*0.7){
                                          //where 0.7 corresponds to 70% --^

确保添加检查,以免同时触发多个 Ajax 请求(如果尚未触发

(。

这超出了问题的范围,但是如果您想要一个如何防止同时触发多个请求的示例:

声明一个全局变量,例如 processing .

然后将其合并到您的函数中:

if (processing)
    return false;
if ($(window).scrollTop() >= ($(document).height() - $(window).height())*0.7){
    processing = true; //sets a processing AJAX request flag
    $.post("url", '<params>', function(data){ //or $.ajax, $.get, $.load etc.
        //load the content to your div
        processing = false; //resets the ajax flag once the callback concludes
    });
}

这是一个使用var来跟踪滚动函数是否有活动的Ajax请求的简单示例,并且它不会干扰您可能拥有的任何其他并发Ajax请求。

编辑:JSFiddle 示例

请注意,使用 % 来测量文档高度可能是一个坏主意,因为每次加载内容时文档的高度都会增加,这使得它触发 Ajax 请求相对远离页面底部(绝对大小明智(。

我建议使用固定值偏移量来防止这种情况(200-700左右(:

if ($(window).scrollTop() >= $(document).height() - $(window).height() - 700){
                                 // pixels offset from screen bottom   --^

示例:JSFiddle

编辑:要在第一个代码中使用百分比重现问题,请加载 50 div 秒。当您加载下一个div时,它只会增加整个文档高度的 2%,这意味着一旦您将这 2% 滚动回文档高度的 70%,就会触发下一个请求。在我的固定示例中,仅当用户位于距屏幕底部定义的绝对像素范围时,定义的底部偏移量才会加载新内容。

快速谷歌搜索get percentage scrolled down会显示此页面作为第一个结果(使用下面的代码,它或多或少地做了你想要的(。 我觉得你在问这里之前没有尝试任何研究。

$(document).scroll(function(e){
    // grab the scroll amount and the window height
    var scrollAmount = $(window).scrollTop();
    var documentHeight = $(document).height();
    // calculate the percentage the user has scrolled down the page
    var scrollPercent = (scrollAmount / documentHeight) * 100;
    if(scrollPercent > 50) {
        // run a function called doSomething
       doSomething();
    }
    function doSomething() { 
        // do something when a user gets 50% of the way down my page
    }
});