如何在文档末尾上方 300px 处触发事件
滚动时,我想在文档结束前 300px 处触发一个事件。
假设我的 HTML 文档的高度是 1000px,窗口视口的高度是 600px,向下滚动 100px 时,应该触发该事件。
我有这段代码,
$(window).scroll(function(){
if ($(window).scrollTop() == $(document).height() - $(window).height() ){
callFunction();
}
});
当滚动到达底部时,这会触发事件。所以我将其修改为
$(window).scroll(function(){
var height = $(window).height() + 300;
if ($(window).scrollTop() == $(document).height() - height ){
callFunction();
}
});
但显然,它似乎是错误的,因为它不起作用。请帮忙。
While scrolling, I want to fire an event 300px before the end of the document.
Say the height of my HTML document is 1000px and the height of the window viewport is 600px, on scrolling 100px down, the event should be fired.
I've this code
$(window).scroll(function(){
if ($(window).scrollTop() == $(document).height() - $(window).height() ){
callFunction();
}
});
This fires the event when the scroll has reached the bottom. So I modified it as
$(window).scroll(function(){
var height = $(window).height() + 300;
if ($(window).scrollTop() == $(document).height() - height ){
callFunction();
}
});
But obviously, it seems to be wrong since it doesn't work. Please Help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
试试这个
工作演示
try this one
Working demo
我认为您遇到的问题是,scrollTop 永远不会具有您正在寻找的完全正确的像素值。你的数学是正确的,但使用 >而不是 == ,你应该会更成功。
I think the problem you are having is that the scrollTop will never have exactly the right pixel value you are looking for. Your math is correct but use a > instead of == and you should be more successful.
我必须稍微修改一下你的脚本,但是这里有一个例子:
I had to modify your script a bit but here is an example: