【问题标题】:How to rewrite this JS Method without the Arrow Functions?如何在没有箭头函数的情况下重写这个 JS 方法?
【发布时间】:2022-01-08 11:35:16
【问题描述】:

我需要从 animate.style 中删除以下方法的箭头函数;我需要在不支持箭头功能的旧版 chromium 浏览器 (40) 上运行此代码。我正在尝试将其转变为传统的遗留函数,但由于我的大脑似乎只使用箭头函数,所以不断出现语法错误。非常感谢您对这一挑战的任何帮助!

const animateCSS = (element, animation, prefix = 'animate__') =>
  // We create a Promise and return it
  new Promise((resolve, reject) => {
    const animationName = `${prefix}${animation}`;
    const node = document.querySelector(element);

    node.classList.add(`${prefix}animated`, animationName);

    // When the animation ends, we clean the classes and resolve the Promise
    function handleAnimationEnd(event) {
      event.stopPropagation();
      node.classList.remove(`${prefix}animated`, animationName);
      resolve('Animation ended');
    }

    node.addEventListener('animationend', handleAnimationEnd, {once: true});
  });

这就是我们使用上述方法的方式,其中还包含一个箭头函数:

animateCSS('.my-element', 'bounce');

// or
animateCSS('.my-element', 'bounce').then((message) => {
  // Do something after the animation
});

【问题讨论】:

  • 顺便说一句,如果您想为旧版浏览器编写代码,我真的建议您查看babel。它将让您利用现代 javascript 的所有功能,同时确保向后兼容性。

标签: javascript jquery css methods arrow-functions


【解决方案1】:

删除 =>。 在功能块之前添加功能关键字。 不要留下任何未包装的块。

const animateCSS = function (element, animation, prefix = 'animate__') {
  // We create a Promise and return it
  new Promise(function (resolve, reject) {
    const animationName = `${prefix}${animation}`;
    const node = document.querySelector(element);

    node.classList.add(`${prefix}animated`, animationName);

    // When the animation ends, we clean the classes and resolve the Promise
    function handleAnimationEnd(event) {
      event.stopPropagation();
      node.classList.remove(`${prefix}animated`, animationName);
      resolve('Animation ended');
    }

    node.addEventListener('animationend', handleAnimationEnd, {once: true});
  });
  }
  
  animateCSS('.my-element', 'bounce');

// or
animateCSS('.my-element', 'bounce').then(function (message) {
  // Do something after the animation
});```

【讨论】:

  • 如果这不起作用,请告诉我。
  • 首先,感谢您的回答。这可以删除箭头,但它会破坏该方法,因为在进行此类修改时动画不起作用。我假设它与返回有关,因为它与箭头函数自动返回,并且由于我们删除了它,现在没有任何返回。
  • 承诺真的有效吗?您能否提供一个完整的动画示例,以便我对其进行测试。
猜你喜欢
  • 2018-12-17
  • 1970-01-01
  • 2019-06-15
  • 1970-01-01
  • 1970-01-01
  • 2020-07-01
  • 1970-01-01
  • 2022-01-14
  • 2021-08-03
相关资源
最近更新 更多