如果元素在视口中,则为JQuery触发器函数

时间:2017-10-18 10:32:17

标签: javascript jquery gsap

我试图让一个函数openAnimation()正常工作,当元素是"在viewport"!

现在,这个特殊功能是GSAP。我每次运行openAnimation()都没有像预期的那样工作。 运行两次并在每次添加in-view类时重复。

- 如何使用此插件运行我的GSAP功能?

https://codepen.io/davide77/pen/qPLoKP

function inView( opt ) {
    if( opt.selector === undefined ) {
        console.log( 'Valid selector required for inView' );
        return false;
    }
    var elems = [].slice.call( document.querySelectorAll( opt.selector ) ),
        once = opt.once === undefined ? true : opt.once,
        offsetTop = opt.offsetTop === undefined ? 0 : opt.offsetTop,
        offsetBot = opt.offsetBot === undefined ? 0 : opt.offsetBot,
        count = elems.length,
        winHeight = 0,
        ticking = false;


    function update() {
        var i = count;
        while( i-- ) {
            var elem = elems[ i ],
                rect = elem.getBoundingClientRect();
            if( rect.bottom >= offsetTop && rect.top <= winHeight - offsetBot ) {
                elem.classList.add( 'in-view' );

                if( once ) {
                    count--;
                    elems.splice( i, 1 );
                }
            } else {
                elem.classList.remove( 'in-view' );
            }
        }
        ticking = false;

    }

    function onResize() {
        winHeight = window.innerHeight;
        requestTick(); 
    }

    function onScroll() {
        requestTick(); 
    }

    function requestTick() {
        if( !ticking ) {
            requestAnimationFrame( update );
            ticking = true;
        }
    }

    window.addEventListener( 'resize', onResize, false );
    document.addEventListener( 'scroll', onScroll, false );
    document.addEventListener( 'touchmove', onScroll, false );

    onResize();
}

inView({
    selector: '.view-poll', // an .in-view class will get toggled on these elements
    once: true, // set this to false to have the .in-view class be toggled on AND off
    offsetTop: 0, // top threshold to be considered "in view"
    offsetBot: 0 // bottom threshold to be considered "in view"
});


// HOW CAN I RUN THIS FUNCTION NOW?

function openAnimation() {

  var rotate = $('.rotate.in-view');
  var scale = $('.scale.in-view');
  var translate = $('.translate.in-view');

  //feature Left

  TweenLite.from(rotate, 1.2, {y:-400, opacity: 0.0, delay:0.0, }, 0.05);
  TweenLite.from(scale, 1.2, {y:-400, opacity: 0.0, delay:0.0, }, 0.05);
  TweenLite.from(translate, 1.2, {y:-400, opacity: 0.0, delay:0.0, }, 0.05);
}

2 个答案:

答案 0 :(得分:0)

您可以使用库jQuery-visible。在它的帮助下,您可以创建一个窗口事件onScroll并检查您的元素是否为#34;可见&#34;,然后调用您的函数。

答案 1 :(得分:0)

您可以使用http://scrollmagic.io/。使用此功能,您可以在滚动或视图中启动任何功能。