我一直在开发一个网站,该网站可以在滚动时从 MySQL 数据库自动加载新内容。 但问题是即使滚动可以忽略不计,它也会加载新内容。我的意思是它在滚动时加载新内容,而不是当我到达页面末尾时。 可滚动部分位于静态框架内。
jQuery 代码:
<script type="text/javascript">
$(document).ready(function() {
var track_load = 0; //total loaded record group(s)
var loading = false; //to prevents multipal ajax loads
var total_groups = <?php echo $total_groups; ?>; //total record group(s)
$('#results').load("autoload_process.php", {'group_no':track_load}, function() {track_load++;}); //load first group
$("#frames").scroll(function() { //detect page scroll
if($(window).scrollTop() + $(window).height() == $(document).height()) //user scrolled to bottom of the page?
{
if(track_load <= total_groups && loading==false) //there's more data to load
{
loading = true; //prevent further ajax loading
$('.animation_image').show(); //show loading image
//load data from the server using a HTTP POST request
$.post('autoload_process.php',{'group_no': track_load}, function(data){
$("#results").append(data); //append received data into the element
//hide loading image
$('.animation_image').hide(); //hide loading image once data is received
track_load++; //loaded group increment
loading = false;
}).fail(function(xhr, ajaxOptions, thrownError) { //any errors?
alert(thrownError); //alert with HTTP error
$('.animation_image').hide(); //hide loading image
loading = false;
});
}
}
});
});
</script>
请大家帮帮我。 `
可能有问题$(window).scrollTop() + $(window).height() == $(document).height()`这部分。
我想跟踪部分而不是窗口的滚动。
最佳答案
假设以下标记有一些变化:
<div class="container">
<div class="scroll-content">
<p>Scroll container</p>
</div>
</div>
CSS
.container {
position: relative;
height: 400px;
width: 300px;
overflow-y: scroll;
}
.scroll-content {
position: relative;
height: 1200px; /* height just added for illustrative purposes */
width: 300px;
background: #849558;
}
这是跟踪滚动位置并在特定范围内触发 ajax 调用的一种方法:
$('.container').scroll( function() {
var fromtop = $(this).scrollTop(),
height = $(this).find('.scroll-content').innerHeight() - $(this).innerHeight();
// In the above line we're finding the height of the scrollable content
// and subtracting the height of the viewable area (or parent container).
if ((height - fromtop) < 50) {
alert('trigger ajax call');
}
});
< 50
代表你的触发范围。将其更改为最适合您的应用程序的值。
此方法的优点是在加载更多内容后,会重新计算内部容器的高度。
这是一个 Fiddle
关于javascript - AJAX 自动加载 HTML5 部分中的滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21397924/