javascript - 将动画函数从 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);
});
}
解决方案
从 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);
}
推荐阅读
- c++ - 在 CLion (MacOS) 中使用 OpenGL 和 GLUT 库时出现链接错误
- java - 根据参数值和低于它的值获取hashmap键
- jquery - 数据表日期选择器格式
- javascript - React 和 Electron,链接事件处理程序
- r - 如何使用正则表达式从 R 中的字符串中提取像 '<9f><98><82>' 这样的字节
- angular - 找不到命令“ng”,但可以安装
- python - 如何将多头熊猫数据框转换为嵌套字典列表
- java - 异常 org.apache.jasper.JasperException: java.lang.NullPointerException 根本原因 java.lang.NullPointerException
- python-3.x - 将 try/except 与 if/else 语句一起使用
- linux - 如何尾随 adb logcat 的输出并在每个新行中执行一个命令