事件监听器在页面加载时自行触发

时间:2018-06-11 18:22:49

标签: javascript ecmascript-6

事件监听器在页面加载时自行触发,但只想通过单击按钮使其激活。解决这个问题的方法是什么?以下是代码:

class IntroAnimations{
    constructor() {

        //global variables
        this.jsLoadingCta    = document.querySelector('#js-loading-cta');
        this.tlRemoveLoading = new TimelineMax();

        //event listeners: ISSUE HERE
        this.jsLoadingCta.addEventListener('click', this.removeLoadingContent(this.tlRemoveLoading));

        //method calls:
        this.loadAnimations(this.jsLoadingCta);

    };

    removeLoadingContent(tl){

        let jsLoadOverlay = document.querySelector('#js-overlay-load');

        tl
        .to(jsLoadOverlay, 1, {width: '100%', ease: Power4.easeInOut})
        .set(jsLoadOverlay, {left: 'auto', right: 0})
        .to(jsLoadOverlay, 1, {width: '0%', ease: Power4.easeInOut})

    }

    loadAnimations(loadingCta){

        //variables
        let jsloadingCompanyintrotextset1 = document.querySelector('#js-loading-company-intro-text-set-1'),
            jsloadingCompanyintrotextset2 = document.querySelector('#js-loading-company-intro-text-set-2'),
            jsloadingCompanyintrotextset3 = document.querySelector('#js-loading-company-intro-text-set-3'),
            tlIntro                       = new TimelineMax();


        //instaniation of SplitText
        let companyIntro1 = new SplitText().configureDomElement(jsloadingCompanyintrotextset1),
            companyIntro2 = new SplitText().configureDomElement(jsloadingCompanyintrotextset2),
            companyIntro3 = new SplitText().configureDomElement(jsloadingCompanyintrotextset3);


        //GSAP Animations
        tlIntro
        .set([companyIntro1, companyIntro2, companyIntro3], {x: 20, opacity: 0})
        .staggerTo(companyIntro1, 1, {x: 0, opacity: 1, ease: Power4.easeOut}, .02)
        .staggerTo(companyIntro2, 1, {x: 0, opacity: 1, ease: Power4.easeOut}, .02, '-=.95')
        .staggerTo(companyIntro3, 1, {x: 0, opacity: 1, ease: Power4.easeOut}, .02, '-=.9')
        .to(loadingCta, 1, {x: 0, opacity: 1, autoAlpha: 1, ease: Power4.easeOut}, '-=.9')

    };
};

谢谢。为什么会这样?它需要绑定吗?

2 个答案:

答案 0 :(得分:1)

我相信因为它被称为那里。尝试将其更改为

this.jsLoadingCta.addEventListener('click', function() {
    this.removeLoadingContent(this.tlRemoveLoading)
})

答案 1 :(得分:1)

当您使用这样的括号this.removeLoadingContent(this.tlRemoveLoading)时,它将在加载时触发。

你需要它,例如this.removeLoadingContent

由于您使用this.tlRemoveLoading所做的一切都是通过new TimelineMax(),而是尝试做类似的事情

    //event listeners: ISSUE HERE
    this.jsLoadingCta.addEventListener('click', this.removeLoadingContent);
removeLoadingContent(){

    let jsLoadOverlay = document.querySelector('#js-overlay-load');
    let tl = new TimelineMax();

    tl
    .to(jsLoadOverlay, 1, {width: '100%', ease: Power4.easeInOut})
    .set(jsLoadOverlay, {left: 'auto', right: 0})
    .to(jsLoadOverlay, 1, {width: '0%', ease: Power4.easeInOut})

}