更改滚动的div不透明度 [英] Change div opacity on scroll

查看:122
本文介绍了更改滚动的div不透明度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何做到这一点,以便当您向下滚动页面时,下一个DIV会淡入上一个DIV?

How can I make it so that when you scroll down the page, the next DIV fades on top of the previous?

我已经设置了这个小提琴以更好地说明它: http://jsfiddle.net/meEf4/176/
例如,如果您位于页面中间,则背景为蓝色.

I've set up this fiddle to illustrate it better: http://jsfiddle.net/meEf4/176/
So for example if you're halfway down the page, the background is blue.

这是jsFiddle的内容,以防万一爆炸并有人遇到类似问题.

Here's the contents of that jsFiddle, in case that ever explodes and somebody is stuck with a similar issue.

<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);
});​

工作演示场

WORKING DEMO FIDDLE

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

You map the scroll value to the background div you need to target using the maxScroll value divided by the number of background divs - 1. This number is the scroll range that one background div has to cover. Then you calculate the scroll percentage for that div by using the scroll value modulus the scroll range, that way you get a value between 1 and 0 for the target div.

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

Then you set your target div to the calculated value, the divs below have opacity 1, the divs above it have opacity 0 (because they went through their range of 1 to 0 before)

这篇关于更改滚动的div不透明度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆