2017-04-06 92 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景王在這裏的意思是*非常非常大* –

相關問題