簡體   English   中英

淡出頁面頂部部分,淡入頁面底部

[英]Fade out section on page top, fade in on bottom

我得到了這個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個部分。 有沒有一種方法可以添加更多部分,當它們到達頂部並從底部逐漸消失時,它們就會淡出?

據我了解,您需要這樣的東西:當一個元素進入視口區域時,它會淡入,而當它離開視口區域時,則應淡出。

因此,所有操作都應在窗口的onscroll事件中完成。 要知道該元素是否在視口區域之內和之外,我們需要了解其topbottom (可以通過其topheight來計算),我們還需要了解視口的高度。 這就是我們需要確定元素是否在視口區域中或視口區域之外的所有內容。 以下是詳細的代碼。 注意:為簡單起見,這里不包括獲取視口高度的復雜性(我只使用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);
  });           
});

演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM