I need to retrieve the visible height of a div within a scrollable area. I consider myself pretty decent with jQuery, but this is completely throwing me off.
假设我在一个黑色包装中有一个红色的div:
在上图中,jQuery函数将返回248,即div的可见部分.
Once the user scrolls past the top of the div, as in the above graphic, it would report 296.
Now, once the user has scrolled past the div, it would again report 248.
显然,我的数字不会像这个演示中那样一致和清晰,或者我只需要对这些数字进行硬编码.
I have a bit of a theory:
- 获取窗口的高度
- Get the height of the div
- 获取div相对于窗口顶部的初始偏移量
- 在用户滚动时获取偏移量.
这看起来很简单,但我就是想不起来.明天早上我要再喝一杯;我只是想你们中的一些天才也许能帮上忙.
Thanks!
更新:这是我自己想出来的,但是看起来下面的答案中的一个更优雅,所以我将改用它.对于好奇的人,我想出了以下几点:
$(document).ready(function() {
var windowHeight = $(window).height();
var overviewHeight = $("#overview").height();
var overviewStaticTop = $("#overview").offset().top;
var overviewScrollTop = overviewStaticTop - $(window).scrollTop();
var overviewStaticBottom = overviewStaticTop + $("#overview").height();
var overviewScrollBottom = windowHeight - (overviewStaticBottom - $(window).scrollTop());
var visibleArea;
if ((overviewHeight + overviewScrollTop) < windowHeight) {
// alert("bottom is showing!");
visibleArea = windowHeight - overviewScrollBottom;
// alert(visibleArea);
} else {
if (overviewScrollTop < 0) {
// alert("is full height");
visibleArea = windowHeight;
// alert(visibleArea);
} else {
// alert("top is showing");
visibleArea = windowHeight - overviewScrollTop;
// alert(visibleArea);
}
}
});