简体   繁体   中英

Fade element opacity on scroll based off window width

I'm trying to fade in an element based off when it first enters the viewport then have it equal 100% opacity by the time it hits the end of the viewport. I have working as far as reaching 100% opacity when it gets to the end. However, when it starts animating, it starts out at about 60% which I know is because I am basing it off the scroll position. So my question is how can I calculate the opacity starting at 0 once it enters the viewport?

This is what I have so far:

$('.left-cont').each(function() {
    var $this     = $(this),
        leftPos   = $this.offset().left,
        fadeStart = leftPos - winWidth,
        fadeUntil = leftPos,
        opacity;

        console.log( winWidth - (leftPos - scrollPos));
        console.log(fadeStart);

    if( scrollPos <= fadeStart ) {
        opacity = 0;
    }
    else {
        opacity = scrollPos/fadeUntil;
    }

    $this.css({
        'opacity': opacity
    });
});

I can provide more context if needed. Any help is appreciated.

1) Is this jQuery function only executed once or is it placed inside the onScroll-binded function?

$( window ).scroll(function() {

  /* get scroll top and left values here */

  $( ".box" ).each(function(){

    /* do position check and css adjustments here */

  });

});

2) The calculation for the opacity is: (1 - ((box_offsetTop - scrollTop) / windowHeight))

3) I made a working example here for scrolling vertically: http://jsfiddle.net/0mks8eut/1/

You can change it to calculate opacity based on horizontal scrolling by (un)commenting the other calculation inside the function.

! Make sure that there is enough content (or padding/margin) after/next to the object. Otherwise it will never reach opacity:1 (eg the top/left of the screen).

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