Change the opacity based on elements current offset

雨燕双飞 提交于 2019-12-10 15:12:59

问题


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/



来源:https://stackoverflow.com/questions/17327318/change-the-opacity-based-on-elements-current-offset

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!