淡出页面顶部,淡入底部

时间:2017-04-06 15:34:07

标签: javascript jquery html css

我得到了这个代码: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个部分。有没有办法可以添加更多的部分,当它们到达顶部并从底部淡入时它们会淡出?

1 个答案:

答案 0 :(得分: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