Change the opacity based on elements current offse

2019-06-26 16:40发布

问题:

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.

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

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

    ... <= opacity 0

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.

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?

回答1:

you can try

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/
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/