2017-04-06 67 views
0

我得到这个codepen:https://codepen.io/tobiasglaus/pen/NpVXRR
当我滚动第一部分淡出,第二个从这个代码底部在逐渐消失:淡出在页面顶部,淡入底部

$(window).scroll(function(){ 
    $(".top").css("opacity", 1 - $(window).scrollTop()/400); 
    }); 
$(window).scroll(function(){ 
    $(".bottom").css("opacity", 0 + $(window).scrollTop()/400); 
    }); 

但这只是一个滚动事件,只能与2个部分一起工作。有没有办法可以添加更多部分,并且当它们到达顶部并从底部淡入时它们就会淡出?

+0

由于顶部和底部的是类,不能你只是重复利用那些通过您的页面,但是,不同的元素? –

+0

此外,它看起来像你可能可以将这些组合到同一个窗口滚动事件中,所以只需从上面的示例中删除第3行和第4行。 –

+0

@LeeWise不,我不能。因为它只是一个滚动事件,其他部分只会在开始滚动时淡入淡出(在其他部分的下面),但我试图实现的是它们在顶部淡出并淡入底部(如在小提琴中答案如下)。是的,我知道我可以结合这两个功能:) –

回答

3

据我所知,你想要的东西是这样的:当一个元素进入视口区域时,它会消失,当它从视口区域出来时,它应该淡出。

所以所有的事情都应该在窗口的onscroll事件中完成。要知道元素是否进出视口区域,我们需要知道其中的topbottom(可以从其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

+0

你是真正的“国王”!完美的作品。但是当我改变divs高度时,'var opacity'似乎并不正确。例如,它从“不透明度:0.9”跳到“不透明度:0.6”。我必须改变一些数学吗? –

+0

@TobiasGlaus这是你为你的div高度设置的确切值吗?此外,BTW当前代码仅在顶部边缘到达视口的顶部边缘时才为div设置1的最大不透明度。因此,如果div在视口中完全可见,但其顶部边缘仍处于中间位置,则它们的不透明度仍将小于1.是否希望div完全变为不透明(完全可视)(完全包含在视口中)? –

+0

btw景王在这里的意思是*非常非常大* –