简体   繁体   English

使用jQuery检测div顶部的滚动距离,而不是从页面顶部检测滚动距离

[英]Using jQuery to detect scroll distance from the top of a div, not from top of page

So here's the deal. 所以这是交易。 I have a div (call it div.container for troubleshooting purposes) on my page that will hold dynamically loaded content from a database (loaded using PHP). 我在我的页面上有一个div(称为div.container用于故障排除),它将保存来自数据库的动态加载内容(使用PHP加载)。 I want to detect the user's scroll position from the top of div.container, not from the top of the page. 我想从div.container的顶部检测用户的滚动位置,而不是从页面顶部检测。 Note, div.container is not positioned at the top of the page, but is a child div with a position roughly 50px from the top of the page. 请注意,div.container不是位于页面顶部,而是一个子div,其位置大约距离页面顶部50px。 I am looking to get the scroll distance in pixels. 我希望得到滚动距离(以像素为单位)。

I tried this with zero success: 我试过这个没有成功:

$("div.container").scrollTop();

Other than that, I really have no idea where to start with this. 除此之外,我真的不知道从哪里开始。 Any help is so greatly appreciated. 任何帮助都非常感激。 Thanks much. 非常感谢。

You need to get the window's scrollTop() and subtract the '.container' offset() top value: 你需要得到窗口的scrollTop()并减去'.container' offset()最高值:

$(window).scroll(function(){
    var posTop = $(window).scrollTop() - $('.container').offset().top
});

See this jsfiddle demo . 看到这个jsfiddle演示

使用偏移来计算子div与父div的距离,

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM