$(window).scroll(function() {
if($(window).scrollTop() == $(document).height() - $(window).height()) {
// ajax call get data from server and append to the div
}
});
<!DOCTYPE html>
<html>
<head>
<title>Demo: Lazy Loader</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<style>
#myScroll {
border: 1px solid #999;
}
p {
border: 1px solid #ccc;
padding: 50px;
text-align: center;
}
.loading {
color: red;
}
.dynamic {
background-color:#ccc;
color:#000;
}
</style>
<script>
var counter=0;
$(window).scroll(function () {
if ($(window).scrollTop() == $(document).height() - $(window).height() && counter < 2) {
appendData();
}
});
function appendData() {
var html = '';
for (i = 0; i < 10; i++) {
html += '<p class="dynamic">Dynamic Data : This is test data.<br />Next line.</p>';
}
$('#myScroll').append(html);
counter++;
if(counter==2)
$('#myScroll').append('<button id="uniqueButton" style="margin-left: 50%; background-color: powderblue;">Click</button><br /><br />');
}
</script>
</head>
<body>
<div id="myScroll">
<p>
Contents will load here!!!.<br />
</p>
<p >This is test data.<br />Next line.</p>
<p >This is test data.<br />Next line.</p>
<p >This is test data.<br />Next line.</p>
<p >This is test data.<br />Next line.</p>
<p >This is test data.<br />Next line.</p>
<p >This is test data.<br />Next line.</p>
<p >This is test data.<br />Next line.</p>
<p >This is test data.<br />Next line.</p>
<p >This is test data.<br />Next line.</p>
<p >This is test data.<br />Next line.</p>
<p >This is test data.<br />Next line.</p>
<p >This is test data.<br />Next line.</p>
<p >This is test data.<br />Next line.</p>
<p >This is test data.<br />Next line.</p>
<p >This is test data.<br />Next line.</p>
<p >This is test data.<br />Next line.</p>
<p >This is test data.<br />Next line.</p>
<p >This is test data.<br />Next line.</p>
<p >This is test data.<br />Next line.</p>
<p >This is test data.<br />Next line.</p>
<p >This is test data.<br />Next line.</p>
<p >This is test data.<br />Next line.</p>
</div>
</body>
</html>
如果不是所有的文档滚动,比如说,当文档中有一个滚动 div时,那么上述解决方案如果不进行适应性调整就无法工作。下面是如何检查 div 的滚动条是否已经触底:
$('#someScrollingDiv').on('scroll', function() {
let div = $(this).get(0);
if(div.scrollTop + div.clientHeight >= div.scrollHeight) {
// do the lazy loading here
}
});
var scrollLoad = true;
$(window).scroll(function(){
if (scrollLoad && ($(document).height() - $(window).height())-$(window).scrollTop()<=800){
// fetch data when we are 800px above the document end
scrollLoad = false;
}
});
$(window).scroll(function() {
if(Math.ceil($(window).scrollTop())
== Math.ceil(($(document).height() - $(window).height()))) {
// ajax call get data from server and append to the div
}
});
或允许在滚动到底之前从服务器加载数据。
if ($(window).scrollTop() >= ($(document).height() - $(window).height() - 200)) {
// Load data
}