我正在尝试计算可见(屏幕上)元素相对于视口高度的比率(百分比)(而不是屏幕元素的百分比!)。元素总是100%宽度,因此,在任何给定点,屏幕上总是最多有2个元素,即上面元素的一部分,下面一个元素。到目前为止,我能够编写正确计算顶部元素的代码,但下面的元素(在第一个元素之后)仍然是错误的。我究竟做错了什么?
<section id="0" class="window" style="height: 150vh; background-color: #004444">
<div class="smth"></div>
</section>
<section id="1" class="window" style="height: 150vh; background-color: #003333">
<div class="smth"></div>
</section>
<section id="2" class="window" style="height: 150vh; background-color: #002222">
<div class="smth"></div>
</section>
$.fn.isOnScreen = function(){
var win = $(window);
var viewport = {
top : win.scrollTop(),
left : win.scrollLeft()
};
viewport.right = viewport.left + win.width();
viewport.bottom = viewport.top + win.height();
var bounds = this.offset();
bounds.right = bounds.left + this.outerWidth();
bounds.bottom = bounds.top + this.outerHeight();
return (!(viewport.right < bounds.left || viewport.left > bounds.right || viewport.bottom < bounds.top || viewport.top > bounds.bottom));
};
$.fn.ratioVisible = function(){
var s = $(window).scrollTop();
if(!this.isOnScreen()) return 0;
var curPos = this.offset();
var curTop = curPos.top - s;
var screenHeight = $(window).height();
var blockHeight = this.height();
var ratio = ((curPos.top + blockHeight - s) / screenHeight);
if(ratio > 1) ratio = 1 - (ratio - 1);
return ratio;
};