javascript - 在页面顶部淡出部分,在底部淡入

标签 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 个部分。有没有一种方法可以让我添加更多部分,当它们到达顶部并从底部淡入时,它们就淡出?

最佳答案

据我所知,您想要这样的东西:当一个元素进入视口(viewport)区域时,它会淡入,而当它离开视口(viewport)区域时,它应该淡出。

所以所有的事情都应该在窗口的onscroll 事件中完成。要知道元素是否在视口(viewport)区域内外,我们需要知道它的 topbottom(可以从它的 top 及其高度),我们还需要知道视口(viewport)的高度。这就是我们需要确定元素是否在视口(viewport)区域之内的全部内容。下面是详细的代码。注意:为了简单起见,我在这里不包括获取视口(viewport)高度的复杂性(我只使用 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

关于javascript - 在页面顶部淡出部分,在底部淡入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43259623/

相关文章:

jquery - 使用 fancybox 生成缩略图库

jquery - 将动画顺序添加到 animate.css

javascript - 将元素绝对定位在部分底部会添加不需要的第二个滚动条

javascript - 使用 Select2 和其他表单控制元素或 input-group-btn 响应修复输入组

javascript - 将导航链接更改为按钮,使其看起来与打开并加载外部 div 相同

javascript - 我如何使用 webpack 来要求包含内联 CSS、JS 和 PNG 的 HTML 文档

javascript - jquery-bootgrid 如何在隐藏列中搜索

html - MathJax 中\newcommand 宏不需要的额外空间

javascript - 如何在 d3.js 的多焦点强制布局中动态更新焦点

javascript - 为什么 PreventDefault() 不停止此表单提交的重定向?