简体   繁体   English

基于窗口宽度滚动时的淡入淡出元素不透明度

[英]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. 我试图在元素第一次进入视口时淡入淡出,然后在其到达视口末端时使其不透明度等于100%。 I have working as far as reaching 100% opacity when it gets to the end. 当达到终点时,我一直努力达到100%的不透明度。 However, when it starts animating, it starts out at about 60% which I know is because I am basing it off the scroll position. 但是,当它开始动画时,它以大约60%的速度开始,我知道这是因为我将其置于滚动位置之外。 So my question is how can I calculate the opacity starting at 0 once it enters the viewport? 所以我的问题是,一旦进入视口,如何计算从0开始的不透明度?

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? 1)这个jQuery函数是只执行一次还是放在onScroll-binded函数内部?

$( 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)) 2)不透明度的计算公式为: (1 - ((box_offsetTop - scrollTop) / windowHeight))

3) I made a working example here for scrolling vertically: http://jsfiddle.net/0mks8eut/1/ 3)我在这里做了一个垂直滚动的工作示例: 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). 否则,它将永远不会达到opacity:1 (例如,屏幕的顶部/左侧)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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