简体   繁体   English

jQuery淡入/淡出滚动公式

[英]Jquery Fade In/Out Scroll Formula

I have images that fade in and out as you scroll down on the page. 当您向下滚动页面时,我的图像会淡入淡出。 The issue I am having is that the opacity is changing as soon as you begin to scroll. 我遇到的问题是,一旦开始滚动,不透明度就会改变。

Here is the formula: 公式如下:

$(document).ready(function(){
    $(window).scroll(function(){
        $(".tre").css("opacity", 1 - $(window).scrollTop() / 500);
    });
});

$(document).ready(function(){
    $(window).scroll(function(){
        $(".two").css("opacity", 0 + $(window).scrollTop() / 500);
    });
});

As I understand it, one image fades out when scrolled down 500 pixels and the other fades in at that point. 据我了解,当向下滚动500像素时,一张图像会淡出,而另一张图像则在该点处淡入。

What I want to do is just start the opacity change later in the scroll. 我想做的只是稍后在滚动中开始不透明度更改。 How do I start the opacity change at 500 pixels down, and then the change would occur from pixels 500-1000. 我如何开始将不透明度从500像素下移,然后从500-1000像素发生变化。

Thanks 谢谢

EDIT 编辑

Not sure it'll even work with this code now, might need something completely different. 不确定现在是否可以使用此代码,可能需要完全不同的东西。

To find the fraction that scroll has moved through a range you could use a function like this: 要查找滚动范围内的分数,可以使用如下函数:

function fraction_that_scroll_has_moved_through_range( start, end )
{
    if( start < 0 || end <= start )
        return 0;

    var range = end - start;
    var current_pos = $(window).scrollTop() - start;
    var fraction = current_pos / range;

    if( fraction < 0 )
        fraction = 0;
    else if( fraction > 1 )
        fraction = 1;

    return fraction;
}

and then in your example call it like so: 然后在您的示例中这样调用它:

$(document).ready(function(){
    $(window).scroll(function(){
        var f = fraction_that_scroll_has_moved_through_range( 500, 1000 );
        $(".tre").css("opacity", 1 - f );
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM