gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 22:42:57 25 4
gpt4 key购买 nike

我得到了这个代码笔: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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com