据我所知,你想要的东西是这样的:当一个元素进入视口区域时,它会消失,当它从视口区域出来时,它应该淡出。
所以所有的事情都应该在窗口的onscroll
事件中完成。要知道元素是否进出视口区域,我们需要知道其中的top
和bottom
(可以从其top
及其height
中计算),我们还需要了解视区的高度。这就是我们需要查明某个元素是处于视口区域还是视区外的情况。以下是详细的代码。注意:为了简单起见,我没有在这里提到视口高度的复杂性(我只是使用document.documentElement.clientHeight
- 这应该适用于所有现代浏览器的最新版本)。
HTML:
<div class="fading"></div>
<div class="fading"></div>
<div class="fading"></div>
<div class="fading"></div>
CSS:
.fading {
border:1px solid red;
margin-bottom:10px;
height:500px;
background:green;
}
JS:
var fadings = $(".fading");
$(window).scroll(function(){
//the viewport's height
var vpheight = document.documentElement.clientHeight;
//loop through all interested elements
fadings.each(function(){
//get the rect of the current element
var r = this.getBoundingClientRect();
//the current element's height
var thisHeight = $(this).height();
//check if the element is completely out of the viewport area
//to just ignore it (save some computation)
if(thisHeight + r.top < 0 || r.top > vpheight) return true;
//calculate the opacity for partially visible/hidden element
var opacity = Math.max(0, Math.min(1,
(r.top >= 0 ? vpheight - r.top : thisHeight - Math.abs(r.top))/vpheight));
//set the opacity
$(this).css("opacity", opacity);
});
});
Demo
由于顶部和底部的是类,不能你只是重复利用那些通过您的页面,但是,不同的元素? –
此外,它看起来像你可能可以将这些组合到同一个窗口滚动事件中,所以只需从上面的示例中删除第3行和第4行。 –
@LeeWise不,我不能。因为它只是一个滚动事件,其他部分只会在开始滚动时淡入淡出(在其他部分的下面),但我试图实现的是它们在顶部淡出并淡入底部(如在小提琴中答案如下)。是的,我知道我可以结合这两个功能:) –