简体   繁体   中英

fade on EACH element - on scroll

How to do to apply the fade, compared with their height, on each element and not the whole ?

HTML :

<div class="test fade"></div>

CSS :

* {
    padding: 0;
    margin: 0;
    box-sizing: border-box;
}

body {
    font: 1em 'Open Sans', sans-serif;
}

.test {
    height: 70vh;
    width: 30%;
    background-color: rgba(0, 0, 0, 0.6);
    margin: 1em auto;
}

JS :

var $elem = $('.test.fade');
for (var i = 0; i <= 5; i++) {
    $elem.clone().appendTo('body');
}
$(window).scroll(function() {
    var percent = $(this).scrollTop() / ($(document).height() - $(this).height());
    $('.fade').each(function() {
        $(this).css('opacity', 1 - percent);
    });
});

jsfiddle

I suggest using Element.getBoundingClientRect() to calculate the position of the element relative to the viewport.

With its position relative to the viewport, you can calculate how much % of it is outside the viewport and use that as opacity (after conversion to a 0-1 value):

var $elem = $('.test.fade');
for (var i = 0; i <= 5; i++) {
    $elem.clone().appendTo('body');
}
$(window).scroll(function() {
  $('.fade').each(function() {
    var bounds = this.getBoundingClientRect();
    var op = Math.max((bounds.height + Math.min(bounds.top, 0)) / bounds.height, 0);
    $(this).css('opacity', op);
  });
});

Demo JSFiddle here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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