我有一些 div 本质上只是彩色矩形来帮助可视化。当我向下滚动页面时,每个矩形应该fadeIn
or fadeOut
取决于滚动条的位置。不幸的是,它吓坏了,褪色更像是痉挛的频闪灯。我认为最好通过滚动方式通过每个元素的距离来确定不透明度级别,但我什至不知道从哪里开始这种愚蠢的行为。
Seems this guy https://stackoverflow.com/questions/11462751/fade-out-on-scroll有一个类似的问题,但答案不起作用。
FIDDLE http://jsfiddle.net/ruXeq/
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()
and 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();
});
});
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)