javascript - 如何在 if/else 语句中使用 keydown 事件
问题描述
我正在尝试为我的中学科学博览会项目制作一个在线灯泡,并且我想添加一个“复活节彩蛋”,其中会弹出警报。我试图让它在按下某个键时激活。这是我到目前为止的代码:
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Light Bulb</title>
<link href = "file.css" rel = "stylesheet">
</head>
<body>
<button id = "light-switch">Turn on Light</button>
<p id = "lightStatus">Light is off</p>
<p id = "easterEgg"></p>
</body>
<script src="file.js"></script>
</html>
JS
let swt = document.querySelector("#light-switch");
let sta = document.querySelector("#lightStatus");
let egg = document.querySelector("#easterEgg");
let html = document.querySelector("html");
swt.addEventListener("click", updateSwt);
function updateSwt() {
if(swt.textContent === "Turn on Light"){
swt.textContent = "Turn off Light";
swt.style.backgroundColor = "Yellow";
console.log("on");
sta.textContent = "Light is on";
}
else{
swt.textContent = "Turn on Light";
swt.style.backgroundColor = "Black";
console.log("off");
sta.textContent = "Light is off";
}
}
swt.addEventListener("click",updateConsole);
function updateConsole() {
if(swt.click === true) {
console.log("")
}
else{
console.log("swtClick")
}
}
这是我尝试过的
swt.addEventListener("keydown", updateEgg);
function updateEgg() {
if(html.keydown === true){
console.log("easter egg found")
alert("You found the easter egg!!!");
}
else{
console.log("")
}
解决方案
如果我理解正确,那么您的目标可以实现。
html.addEventListener("keydown", updateEgg);
function updateEgg() {
if (event.keyCode == 85 /*checks for u press*/) {
console.log("easter egg found")
alert("You found the easter egg!!!");
}
}
if 语句检查被按下的键是否是'u'。对于键码,您可能会发现https://keycode.info/很有用。
推荐阅读
- typescript - 无法导入 Apollo 解析器
- angular - 仅在 Azure CI 上的 X 超时前断开连接重新连接失败
- varnish - varnish vcc模块如何将vcl编译成C代码?
- spring-boot - 使用带有手动计数器增量的千分尺计时器
- python - 如何在 for 循环中引用与另一列相关的列
- r - 增强的 Dickey-Fuller 检验结果
- windows - WIndows 上的 Puppet:仅当注册表项存在(不)时才创建资源
- javascript - 未捕获的错误:找不到 react-redux 上下文值;请确保组件包装在 <Provider>
- html - 邮件模板 magento 中的 div 断表
- javascript - 将 prop 传递给每个子组件