我正在使用 PHP 和 MySQL 输出一个结果集,每个结果都包装在一个 DIV 中。一旦用户滚动到浏览器窗口底部,JavaScript 函数就会触发一个 Action 。
$(window).scroll(function(){
if ($(window).scrollTop() == $(document).height() - $(window).height()){
trigger_funtion();
}
});
PHP 结果的每个元素(类“.item”)都被放入包含所有元素的通用包装器 DIV(类“.results”)中。
我如何更改上面的这个函数,以便在用户“滚动”或“到达”从结果集创建的最后一个 DIV 时立即触发操作,而不是当他点击浏览器底部时 window ?
下面的方法我都试过了,还是不行
$(window).scroll(function(){
if ($(window).scrollTop() == $(".results .item:last")){
trigger_funtion();
}
});
最佳答案
您需要使用 .position().top我建议使用 >= 而不是 == 因为你不能依赖数字相等
if ($(window).scrollTop() >= $(".results .item:last").position().top)
或
var winHeight = $(window).height(); // viewport
if ($(window).scrollTop()+winHeight >= $(".results .item:last").position().top)
这是最后一项到达顶部的代码
$(function() {
var $item = $(".results .item:last"); // cache element
$(window).scroll(function(){
var itemTop = $item.position().top-10; // subtract some pixels from the item
var winScrollTop =$(window).scrollTop();
window.console && console.log(winScrollTop,itemTop); // remove when happy
if (winScrollTop>=itemTop) {
window.console && console.log("reached!",winScrollTop,itemTop); remove when happy
$item.html("REACHED!");
}
});
});
这里是当它触底时
$(function() {
var $item = $(".results .item:last"); // cache element
$(window).scroll(function(){
var itemTop = $item.position().top-10; // subtract some pixels from the item
var winScrollTop =$(window).scrollTop();
var winHeight = $(window).height();
window.console && console.log(winScrollTop,itemTop); // remove when happy
if (winScrollTop+winHeight>=itemTop) {
window.console && console.log("reached!",winScrollTop,itemTop); // remove when happy
$item.html("REACHED!");
}
});
});
关于javascript - 在 Javascript 中到达目标 div 时触发 Action ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23743508/