在什么元素上使用 onkeydown 属性?

What element to use onkeydown attribute on?

我想在按下 w 键时得到 运行 一个函数,我找到了一些解决方案,但无法确定我们在哪里放置该代码。另外,只要我在同一个网页上,无论何时按 w,我都希望它被执行。

这是我的代码:

HTML

<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" type="text/css" href="style.css">
        <meta charset="utf-8">
        <input type="text" onkeydown="keyPressed()">
    </head>
    <body>
        <div id="screen">
            
        </div>
    </body>
    <script src="main.js"></script>
</html>

Javascript

function keyPressed() {
    // this doesn't run.
}

如果我犯了错误,请告诉我,如果我没有犯错,为什么它不起作用?

如果我理解正确的话,您想“监听”按键事件并专门监听 w。

下面是无需输入即可执行此操作的代码。 您必须单击 window 才能使其正常工作(在网页上无需单击 window 即可正常工作)

function ready(callbackFunction){
    if(document.readyState != 'loading')
        callbackFunction(ev)
    else
        document.addEventListener("DOMContentLoaded", callbackFunction)
}

ready(ev => {
    console.log('DOM is ready.');
// code above checks that the DOM is loaded and ready

    // addEventListener on the window and listen for keydown

    window.addEventListener("keydown", function(e) {

        // Next 4 lines listen for the key and print it to the screen, not really needed.
        let str = "KeyboardEvent: key='" + event.key + "' | code='" + event.code + "'";
        let el = document.createElement("span");
        el.innerHTML = str + "<br/>";
        document.getElementById("screen").appendChild(el);
        
        // this listens for w, add your function in here.
        if (event.key == "w") {
            alert('You pressed lowercase w');
        }

    }, true);

 })
<!DOCTYPE html>
<html>

<head>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  
  <title>My Project</title>
</head>

<body>



<main>
Click in this window to make active. <br>
Then keydown and the key & keycode will show. <br>
keydown lowercase w and it will alert.
<div id="screen"> </div>
</main>

</body>

</html>