简体   繁体   中英

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). I want to detect the user's scroll position from the top of div.container, not from the top of the page. 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. 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:

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

See this jsfiddle demo .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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