更改滚动逻辑的自动加载(防止用户等待)
目前,当用户到达网站底部时,我使用以下逻辑从数据库自动加载新帖子:
$(window).scroll(function() {
if ($(window).scrollTop() == $(document).height() - $(window).height()) {
last_msg_funtion();
}
});
足够了。它做了它应该做的事情,但我想改变这一点,以便当用户距离网站底部 100 像素时它开始加载新帖子。有什么想法吗?当我尝试更改代码时,我要么:
**进入了last_msg_function()调用的几乎无限循环,因为if()语句匹配例如距离底部100个像素并且每个像素下降到0个像素滚动时。因此,如果您滚动得非常慢,您可能会设法停在距底部 100 像素处,但这在现实生活中是行不通的。
**)它必须与我定义的底部像素完全匹配,例如90像素。如果您在例如 89 或 91 像素处停止滚动,它将不会加载任何内容。
那么,我应该更改什么以确保它在您 0 时开始加载 ->距网站底部 100 像素,但同时不会每次都发送新请求以在仍在加载时将滚动位置向任何方向更改几个像素?
谢谢!
Currently, I use the following logic to auto-load new posts from the database when the user reaches the bottom of the site:
$(window).scroll(function() {
if ($(window).scrollTop() == $(document).height() - $(window).height()) {
last_msg_funtion();
}
});
Fair enough. It does what it's supposed to do, but I'd like to change this so it starts loading new posts when the user is e.g. 100 pixels from the bottom of the site. Any ideas? When I've tried changing the code, I've either:
** entered an almost endless loop of last_msg_function() calls, because the if() statement matches e.g. from 100 pixels away from the bottom and for every pixel down to 0 pixels when scrolling. So, if you scroll real slow, you'll maybe manage to stop at exactly 100 pixels from the bottom, but that's not going to work in real life.
**) it has to match exactly the pixels from the bottom I define, e.g. 90 pixels. If you stop scrolling at e.g. 89 or 91 pixels, it won't load anything.
So, what should I change to make sure it starts loading when you're 0 -> 100 pixels away from the bottom of the site, but at the same time not send a new request every time to change the scroll position a few pixels in any direction while it's still loading?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以稍微更改一下您的支票,如下所示:
您可以在此处尝试。这是检查滚动位置是否距实际底部 0-100px...您可能需要确保
last_msg_function()
如果已经正在加载,则不会执行任何操作(无论如何你都应该这样做),但除此之外,if()
是唯一需要的更改。You can just change your check a bit, like this:
You can give it a try here. This is checking that the scroll position is 0-100px from the actual bottom...you may want to ensure that
last_msg_function()
doesn't do anything if it's already loading (you should do this anyway), but other than that, theif()
is the only change needed.很好的答案,尼克。另一件要做的事情是确保每次用户滚动时滚动函数仅触发一次,否则,正如您所提到的,last_msg_function 将被多次调用。尝试这样的事情......
Good answer Nick. One other thing to do is to make sure that your scroll function only fires once every time you user scrolls, otherwise, as you mentioned, the last_msg_function will be called multiple times. Try something like this...