首页 > 解决方案 > 如何在 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("")
  }

标签: javascript

解决方案


如果我理解正确,那么您的目标可以实现。

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/很有用。


推荐阅读