我正在努力在一个页面上加载大约1000种产品,并考虑采用OnScroll
加载的方法。
以下是我关注的方法:
<ul id="productContainer">
</ul>
JQuery的:
$(document).ready(function() {
var track_load = 0; //total loaded record group(s)
var loading = false; //to prevents multipal ajax loads
var total_groups = 5;
$('#productContainer').load("loadmore",
{'group_no':track_load}, function() {track_load++;});
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() ==
$(document).height()) {
if(track_load <= total_groups && loading==false){
loading=true;
$.post('store/loadmore',{'group_no': track_load},
function(data){
$("#productContainer").append(data).fadeIn();
track_load++; //loaded group increment
loading = false;
});
}
}
});
});
PHP
$items_per_group = 25;
$get_total_rows = /*count from SQL table*/
$total_groups = ceil($get_total_rows/$items_per_group);
if(isset($_POST)){
$group_number = filter_var($_POST["group_no"],
FILTER_SANITIZE_NUMBER_INT, FILTER_FLAG_STRIP_HIGH);
if(!is_numeric($group_number)){
header('HTTP/1.1 500 Invalid number!');
exit();
}
$position = ($group_number * $items_per_group);
/*PHP Query*/
}
此解决方案运行良好,但存在以下问题:
But needed thing is that as soon as user reaches last element of current view then next products shall be loaded.
我如何防止这些问题,然后我会有很好的解决方案。
我也试过以下解决方案:
if($(window).scrollTop() + $(window).height() ==
$(document).height()-`200[height of footer]`) {}
第二个解决方案
var end = $("#copyright").offset().top;<br/>
var viewEnd = $(window).scrollTop() + $(window).height();<br/>
var distance = end - viewEnd;<br/>
if(distance <400{load products ajax}
但似乎没有一个按预期工作
答案 0 :(得分:1)
以下是检查元素在可滚动容器中是否可见的基本概念: http://jsfiddle.net/7fpqcqw1/
window.elementInView = false;
function isScrolledIntoView(elem) {
var $elem = $(elem);
var $window = $(window);
var docViewTop = $window.scrollTop();
var docViewBottom = docViewTop + $window.height();
var elemTop = $elem.offset().top;
var elemBottom = elemTop + $elem.height();
window.elementInView = ((elemBottom <= docViewBottom) && (elemTop >= docViewTop)) ? true : false;
return window.elementInView;
}
使用window.elementInView变量,只要你调用isScrolledIntoView(elem),条件只返回true一次而不再调用该函数。
此功能由另一个用户在另一个堆栈溢出问题中提供:Check if element is visible after scrolling