我怎样才能做到当你向下滚动页面时,下一个 DIV 会在前一个 DIV 之上淡出?
我设置了这个小提琴来更好地说明它:http://jsfiddle.net/meEf4/176/ http://jsfiddle.net/meEf4/176/
例如,如果您位于页面的中间,则背景为蓝色。
编辑:这是 jsFiddle 的内容,以防它爆炸并且有人遇到类似的问题。
<style>
html, body, #red, #green, #blue { height: 100%}
#container { height: 300%}
#red, #green, #blue {
position: fixed;
top: 0;
width: 100%;
}
#red { background:red; z-index: 5}
#blue { background:blue; z-index: 4}
#green { background:green; z-index: 3}
</style>
<div id="container">
<div id="red"></div>
<div id="blue"></div>
<div id="green"></div>
</div>
你可以这样做:
var target = $('div.background');
var targetHeight = target.height();
var containerHeight = $('#container').outerHeight();
var maxScroll = containerHeight - targetHeight;
var scrollRange = maxScroll/(target.length-1);
$(document).scroll(function(e){
var scrollY = $(window).scrollTop();
var scrollPercent = (scrollRange - scrollY%scrollRange)/scrollRange;
var divIndex = Math.floor(scrollY/scrollRange);
target.has(':lt(' + divIndex + ')').css('opacity', 0);
target.eq(divIndex).css('opacity', scrollPercent);
target.has(':gt(' + divIndex + ')').css('opacity', 1);
});
工作演示小提琴 http://jsfiddle.net/meEf4/222/
您可以使用以下命令将滚动值映射到需要定位的背景 divmaxScroll value
除以the number of background divs - 1
。这个数字是一个背景 div 必须覆盖的滚动范围。然后,您可以使用以下方法计算该 div 的滚动百分比scroll value
模数the scroll range
,这样您就可以为目标 div 获得一个介于 1 和 0 之间的值。
然后将目标 div 设置为计算值,下面的 div 的不透明度为 1,上面的 div 的不透明度为 0(因为它们之前经历过 1 到 0 的范围)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)