Yah*_*hoo 30 javascript ajax jquery scroll scrollbar
我正在使用以下代码,当滚动条到达底部时,该代码正在工作,
if($(window).scrollTop() == $(document).height() - $(window).height()){
Run Code Online (Sandbox Code Playgroud)
但是我希望当我达到70%的卷轴而不是100时,ajax会被触发.
Fab*_*tté 85
如果您当前的支票在滚动到页面底部时触发,您可以尝试一些基本的算术:
if ($(window).scrollTop() >= ($(document).height() - $(window).height())*0.7){
//where 0.7 corresponds to 70% --^
Run Code Online (Sandbox Code Playgroud)
如果您还没有,请确保添加一个检查以不同时触发多个Ajax请求.
这超出了问题的范围,但是如果您想要一个如何防止同时触发多个请求的示例:
声明一个全局var,例如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
});
}
Run Code Online (Sandbox Code Playgroud)
这是一个使用var来跟踪滚动函数是否存在活动Ajax请求的简单示例,它不会干扰您可能拥有的任何其他同时发生的Ajax请求.
编辑:JSFiddle示例
请注意,使用%来测量文档高度可能是一个坏主意,考虑到每次加载文档时文档的高度都会增加,使得它触发Ajax请求相对更远离页面底部(绝对大小)明智的).
我建议使用固定值偏移来防止(200-700左右):
if ($(window).scrollTop() >= $(document).height() - $(window).height() - 700){
// pixels offset from screen bottom --^
Run Code Online (Sandbox Code Playgroud)
示例:JSFiddle
编辑:要在第一个代码中使用百分比重现问题,请将50 div
秒加载到其中.当你加载下一个时div
,它只会增加总文档高度的2%,这意味着一旦你将这些2%滚动回到文档高度的70%,下一个请求就会被触发.在我的固定示例中,仅当用户处于距屏幕底部的定义的绝对像素范围时,定义的底部偏移才会加载新内容.
Dae*_*ica 13
快速谷歌搜索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
}
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
56895 次 |
最近记录: |