gpt4 book ai didi

javascript - 在 jQuery 滚动条上淡入淡出 div

转载 作者:太空宇宙 更新时间:2023-11-04 13:19:56 27 4
gpt4 key购买 nike

我有几个 div,它们本质上只是彩色矩形以帮助可视化。当我向下滚动页面时,每个矩形应该 fadeInfadeOut 取决于滚动条位置。不幸的是,它吓坏了,褪色更像是痉挛性频闪灯。我认为最好根据我在每个元素中滚动的距离来确定不透明度级别,但我什至不确定从哪里开始这种愚蠢行为。

似乎this guy有一个类似的问题,但答案没有用。

FIDDLE

jQuery

$(document).ready(function(){
var $element_array = $("#content").find("div");
$(window).scroll(function(){
$element_array.each (function(){
if (($(this).position().top + $(this).height()) < $(window).scrollTop())
$(this).fadeIn();
if (($(this).position().top + $(this).height()) > $(window).scrollTop())
$(this).fadeOut();
});
});
});

HTML

<div id="content">
<div id="bg1"></div>
<div id="bg2"></div>
<div id="bg3"></div>
</div>

CSS

html,body{height:100%;margin:0;}
#content{
background:#333333;
height:2000px;
z-index:1;
}
#bg1{
background:blue;
height:400px;
width:100%;
z-index:2;
position:fixed;
top:100px;
display: none;
}
#bg2{
background:green;
height:400px;
width:100%;
z-index:3;
position:fixed;
top:200px;
display: none;
}
#bg3{
background:red;
height:400px;
width:100%;
z-index:4;
position:fixed;
top:300px;
display: none;
}

最佳答案

这里有一些问题

一个问题是 $(this).position().top 为每个 div 返回 0(由于它们的固定性质)。您需要解析实际的 css 值。

第二个是函数 fadeIn()fadeOut() 的性质。如果您在淡出的项目上调用 fadeOut(),如果在您的页面上积极滚动,它就会滞后。 但我没有在下面解决这个问题

我还将 else 放在第一个 if 之后,因为代码路径(应该)是互斥的。

$(document).ready(function(){
var $element_array = $("#content").find("div");
$(window).scroll(function(){
$element_array.each (function(){
if ((parseInt($(this).css('top')) + $(this).height()) < $(window).scrollTop())
$(this).fadeIn();
else if ((parseInt($(this).css('top')) + $(this).height()) > $(window).scrollTop())
$(this).fadeOut();
});
});
});

关于javascript - 在 jQuery 滚动条上淡入淡出 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19258544/

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