首页 > 解决方案 > 将动画函数从 jQuery 转换为 vanilla js

问题描述

我正在尝试复制我之前在训练营中使用纯 jQuery 编写的 simon 游戏,并且我想将其转换为 vanilla JS。我知道 jQuery 中的代码当然是最简单的,但我想通过“艰难的方式”变得更好,而不是总是在框架中完成我所有的工作。

所以这是我使用 jQuery 的旧代码,它非常简单易读,但每次我获得添加类和删除它的结果时,它都会添加到所有元素中。

    function animatePress(currentColor) {
  $("#" + currentColor).addClass("pressed");
  setTimeout(function () {
    $("#" + currentColor).removeClass("pressed");
  }, 100);
}

这是我尝试在不使用 jQuery 的情况下获得相同的结果。

function animatePress() {
  let greenBtn = document.getElementById("green");
  let yellowBtn = document.getElementById("yellow");
  let redBtn = document.getElementById("red");
  let blueBtn = document.getElementById("blue");
  let allButtons = [greenBtn, yellowBtn, redBtn, blueBtn];

  allButtons.forEach(function (e) {
    e.classList.add("pressed");
    setTimeout(() => {
      e.classList.remove("pressed");
    }, 100);
  });
}

标签: javascriptjquery

解决方案


从 jQuery 版本到纯 javascript 的翻译

function animatePress(currentColor) {
  const button = document.querySelector('#' + currentColor);
  button.classList.add("pressed");
  setTimeout(function(){
    button.classList.remove("pressed")
  }, 100);
}

es6版本:

const animatePress = currentColor => {
  const button = document.querySelector(`#${currentColor}`);
  button.classList.add("pressed");
  setTimeout(() => button.classList.remove("pressed"), 100);
}

推荐阅读