我有一些div,这些div实际上只是彩色矩形,有助于可视化。当我向下滚动页面时,每个矩形应fadeIn
或fadeOut
取决于滚动条的位置。不幸的是,它会突然跳出来,并且随着频闪的频闪而逐渐消失。我认为最好通过滚动浏览每个元素的距离来确定不透明度级别,但是我什至不知道从何而来开始如此愚蠢。
似乎这个人有类似的问题,但答案没有用。
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();
});
});
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句