我使用下面的代码发送ajax请求,以便在向下滚动事件中获得更多产品。但是,当我向上滚动时它也会发送ajax请求,这不是预期的。如何修改它以便仅在我将其滚动到底部时发送请求?
_debug = true;
function dbg(msg) {
if (_debug) console.log(msg);
}
$(document).ready(function () {
$(".item-block img.lazy").lazyload({
effect: "fadeIn"
});
doMouseWheel = 1;
$("#result").append("<p id='last'></p>");
dbg("Document Ready");
var scrollFunction = function () {
dbg("Window Scroll Start");
/* if (!doMouseWheel) return;*/
var mostOfTheWayDown = ($('#last').offset().top - $('#result').height()) * 2 / 3;
dbg('mostOfTheWayDown html: ' + mostOfTheWayDown);
dbg('doMouseWheel html: ' + doMouseWheel);
if ($(window).scrollTop() >= mostOfTheWayDown) {
$(window).unbind("scroll");
dbg("Window distanceTop to scrollTop Start");
$('div#loadMoreComments').show();
doMouseWheel = 1;
dbg("Another window to the end !!!! " + $(".item-block:last").attr('id'));
$.ajax({
dataType: "html",
url: "search_load_more.php?lastComment=" + $(".item-block:last").attr('id') + "&" + window.location.search.substring(1),
success: function (html) {
doMouseWheel = 0;
if (html) {
$("#result").append(html);
dbg('Append html: ' + $(".item-block:first").attr('id'));
dbg('Append html: ' + $(".item-block:last").attr('id'));
$("#last").remove();
$("#result").append("<p id='last'></p>");
$('div#loadMoreComments').hide();
$("img.lazy").lazyload({
effect: "fadeIn"
});
$(window).scroll(scrollFunction);
} else {
//Disable Ajax when result from PHP-script is empty (no more DB-results )
$('div#loadMoreComments').replaceWith("<center><h1 style='color:red'>No more styles</h1></center>");
doMouseWheel = 0;
}
}
});
}
};
$(window).scroll(scrollFunction);
});
答案 0 :(得分:0)
您需要检测滚动的方向并将其添加为布尔检查。 This post涵盖了它。
他们提供的摘录:
var lastScrollTop = 0;
$(window).scroll(function(event){
var st = $(this).scrollTop();
if (st > lastScrollTop){
// downscroll code
} else {
// upscroll code
}
lastScrollTop = st;
});
所以你可能会做类似的事情:
$(window).scrollTop() >= mostOfTheWayDown && st > lastScrollTop
答案 1 :(得分:0)
我已更改以下行
if ($(window).scrollTop() >= mostOfTheWayDown)
到
if( $(window).height() + $(window).scrollTop() == $(document).height())
这对我有用。希望这也可以帮助别人。感谢