滚动达到80%时加载ajax

我正在使用以下代码,当滚动条到达底部时,该代码正在工作,

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

然而,我希望当我达到70%的卷轴而不是100时,ajax会被触发。

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

 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", '', 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 } });