[英]Find visible height of div element while scrolling
请咨询该小提琴http://jsfiddle.net/abhicodes/LasxP/
在这里,我想找出每次滚动时#content-wrapper
可见高度。 #header
始终具有相同的高度,并且将固定不变,但是某些页面中的页脚高度不同,因此无法将当前页脚高度作为标准。
如果到达页面末尾,则大多数区域都由页脚覆盖,那么我也只希望#content-wrapper
的可见部分,其余部分都发生在滚动条中。 对于页脚不可见的页面其余部分,我可以减去页眉高度以得到可见的部分。
假设如果我们在页面底部,并且视口高度为600px,那么我想找出用户可以看到多少#content-wrapper
区域。 因为那时还有页脚可容纳100px,页眉可容纳80px,所以#content-wrapper
总可见高度将为600-180 = 420px,类似地,如果我们位于顶部,则页脚不存在,仅页眉在那里,因此#content-wrapper
可见区域将为520px。
因此,故事的寓意是,如果您考虑此小提琴,我想在滚动期间的任何给定实例中找出用户可以看到多少#content-wrapper
高度
尝试
var $win = $(window);
var $footer = $("#footer");
$(window).scroll(function(){
var windowHeight = $win.height();
var footerTop = $footer.offset().top - $win.scrollTop();
var visibleHeight = Math.min(windowHeight, footerTop) - 80;
console.log(windowHeight +", " + footerTop + ", " + visibleHeight);
});
逻辑很简单。
[1]
或[2]
-标头的高度=您的答案。 以下内容将为您提供可见的高度,并分离出变量,使计算有意义:
$(document).on('scroll', function() {
//Container
var cont = $("#content-container");
//Scroll Position (varies with scroll)
var pageTop = $(document).scrollTop();
//Visible Page Size (fixed)
var pageSize = $(window).height();
//Header Height (fixed)
var headerHeight = $('#header').height();
//Content top (fixed)
var contTop = cont.offset().top;
//Content top position (varies with scroll)
var contTopPos = contTop - pageTop;
//Content bottom (fixed)
var contBottom = cont.height() + contTop;
//Content position in relation to screen top (varies with scroll)
var contBottomPos = contBottom - pageTop;
/*
VISIBLE AREA
Take the size of screen/page, unless the bottom of the content further up
and subtract from it
The header height, unless the top of the content is below the header
*/
var visibleArea = Math.min(pageSize, contBottomPos) - Math.max( headerHeight, contTopPos);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.