根据元素当前偏移更改不透明度 [英] Change the opacity based on elements current offset

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

问题描述

我尝试根据每个当前偏移量为某些图像设置不透明度。问题是,如果向下滚动,不透明度不等于所有图像。

I try to set the opacity for some images, based on each current offset. The problem is, that the opacity is not equal to all images if you scroll far down.

这是我尝试完成的,每个 image:

That's what I try to accomplish, for each image:

################
#              #
#              #
#              #
#   === <= opacity 1
#              #
#   *** <= opacity 0.6
#              #
################

    ... <= opacity 0

目前它仅适用于前2-3张图像。所有进一步的下来都不是从 0-1 设置,而是从 0.5-40 设置,否则。

Currently it works only for the first ~2-3 images. All further down are not set from 0-1, rather than from 0.5-40 or else.

另一个问题是,如果滚动偏移是 0 ,则所有图像都被隐藏...

Another problem is, that if the scroll-offset is 0, all images are hidden...

这就是我到目前为止所做的:

That's what I've done so far:

var $win = $(window);
var $img = $('img');

$win.on('scroll', function () {
    var scrollTop = $win.scrollTop();

    $img.each(function () {
        var $self = $(this);

        $self.css({
            opacity: scrollTop / $self.offset().top
        });
    });

}).scroll();

http://jsfiddle.net/ARTsinn/c5SUC/0/

任何想法如何实现这项工作?

Any ideas how to get that work?

推荐答案

你可以尝试

var $win = $(window);
var $img = $('img');

$win.on('scroll', function () {
var scrollTop = $win.scrollTop();

$img.each(function () {
    var $self = $(this);
    var prev=$self.prev().offset();
    var pt=0;
    if(prev){
        pt=prev.top;        
    }
    $self.css({
        opacity: (scrollTop-pt)/ ($self.offset().top-pt)
    });
    console.log(scrollTop+" / "+$self.offset().top+"-"+pt);
});

}).scroll();    

http://jsfiddle.net/mQHEs/

编辑

http://jsfiddle.net/mQHEs/
EDIT

var $win = $(window);
var $img = $('img');

$win.on('scroll', function () {
var scrollTop = $win.scrollTop();

$img.each(function () {
    var $self = $(this);
    var prev=$self.prev().offset();
    if(prev){
        var pt=0;
        pt=prev.top;    
        $self.css({
            opacity: (scrollTop-pt)/ ($self.offset().top-pt)
        });
    }
    else{          //SHOW FIRST IMG
        $self.css({
            opacity: 1
        });
    }  
});

}).scroll();     

http://jsfiddle.net/mQHEs/1/

这篇关于根据元素当前偏移更改不透明度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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