【问题标题】:Javascript “addEventListener” function triggered auto when page loaded [duplicate]页面加载时,Javascript“addEventListener”函数自动触发[重复]
【发布时间】:2021-05-15 11:53:11
【问题描述】:

这是我的代码:

    const start = document.querySelector('#start');

function AnimationCaller(elParam, name, duration, count, fillMode){
    const element = document.querySelector(elParam);
    element.style.animationName  = name;
    element.style.animationDuration  = duration;
    element.style.animationIterationCount = count;
    element.style.animationFillMode= fillMode;
}

AnimationCaller('.circle-1', 'bounce', '3s', 'infinite');
AnimationCaller('.right-back-foo', 'scale', '6s', 'infinite');

start.addEventListener('click', AnimationCaller('.landing-page', 'slide', '2s', null, 'forwards'))

我希望在单击“开始”对象时运行“AnimationCaller”函数。但是,当页面加载时,“AnimationCaller”会自动工作。这是什么原因,我该如何解决?

【问题讨论】:

标签: javascript function onclicklistener addeventlistener


【解决方案1】:

改变这一行

start.addEventListener('click', () => AnimationCaller('.landing-page', 'slide', '2s', null, 'forwards'))

【讨论】:

    【解决方案2】:

    您的问题是您调用函数而不是传递对它的引用。应该可以通过包装来修复。

    start.addEventListener('click', 
        function() { 
             AnimationCaller('.landing-page', 'slide', '2s', null, 'forwards')
        })
    

    【讨论】:

      猜你喜欢
      • 2011-01-23
      • 2014-08-08
      • 1970-01-01
      • 2014-03-21
      • 2021-08-13
      • 1970-01-01
      • 2012-05-05
      • 1970-01-01
      • 2015-02-22
      相关资源
      最近更新 更多