滚动时更改div不透明度

thv*_*v20 7 jquery scroll opacity

我怎样才能这样做,当你向下滚动页面时,下一个DIV会在之前的顶部消失?

我已经设置了这个小提琴来更好地说明它: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>?
Run Code Online (Sandbox Code Playgroud)

Asc*_*iom 7

你可以这样做:

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);
});?
Run Code Online (Sandbox Code Playgroud)

工作演示FIDDLE

使用maxScroll value除以的方法将滚动值映射到需要定位的背景div the number of background divs - 1.此数字是一个背景div必须覆盖的滚动范围.然后使用scroll value模数计算该div的滚动百分比the scroll range,这样您就可以获得目标div的1到0之间的值.

然后将目标div设置为计算值,下面的div具有不透明度1,其上方的div具有不透明度0(因为它们之前经历了1到0的范围)