使用jQuery,我如何找到任何div顶部和视口底部之间的高度?
在我的代码中,我需要在滚动时主动找到页脚顶部和窗口底部之间的距离。
知道怎么做吗?
答案 0 :(得分:2)
一种简单的方法:
function updateScroll () {
// the div whose offset we're measuring:
var measure = $('#measure'),
// the height of the window:
windowHeight = $(window).height(),
// the scroll-distance of the window:
scrollDistance = $(window).scrollTop(),
// how far from the 'top' of the document the div element is:
divOffsetTop = measure.offset().top,
// scrollDistance + windowHeight gives measures how far from the 'top'
// of the document the bottom of the viewport is, subtracting that from
// the offset of the div gives the difference. I used Math.Abs() because
// I didn't know if you wanted to know *just* how far, or if you
// wanted to know if it was 'above' (-difference) or 'below' (+ difference)
// the bottom of the viewport:
delta = Math.abs(divOffsetTop - (scrollDistance + windowHeight));
// setting the text of the div itself, you may want to put that someplace
// else:
$('#distance').text(delta + 'px');
}
// binding the function to the scroll event:
$(window).scroll(updateScroll);
参考文献: