javascript 如何将onkeydown添加到身体?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17593391/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 08:54:41  来源:igfitidea点击:

How to add onkeydown to body?

javascript

提问by GibboK

In my index.html I have this code. I would need to add onkeydownevent to that body in Main.onLoad().

在我的 index.html 中有这个代码。我需要onkeydown在 Main.onLoad() 中向该主体添加事件。

Any idea how to do it?

知道怎么做吗?

<body id="body" 
    onload="Main.onLoad();" 
    onunload="Main.unload();" 
    onmousedown="Main.mouseDown();"
>


<body id="body" 
    onload="Main.onLoad();" 
    onkeydown="TVA.keyDown(event);" 
    onunload="Main.unload();" 
    onmousedown="Main.mouseDown();"
>

采纳答案by Jeff Noel

In a Javascript block, try to use window.onkeydown(MDN).

在 Javascript 块中,尝试使用window.onkeydown( MDN)。

You can also use document.onkeydownand document.body.onkeydown.

您还可以使用document.onkeydowndocument.body.onkeydown

Here is an example for you:

这是一个例子:

JavaScript

JavaScript

document.body.onkeydown = function(e){
    alert(String.fromCharCode(e.keyCode)+" --> "+e.keyCode);
};

Live Demo

现场演示

The code above can be put in any valid JavaScript block (such as Main.onLoad()function).

上面的代码可以放在任何有效的 JavaScript 块中(例如Main.onLoad()函数)。

回答by Teemu

Usually onkeydowncan be attached to the elements which can receive focus. In some browsers you can gain focus to the document.body, but you can't rely on that. windowis one of those elements which can gain the focus.

通常onkeydown可以附加到可以接收焦点的元素上。在某些浏览器中,您可以将注意力集中在 上document.body,但不能依赖于此。window是可以获得焦点的元素之一。

You can try to put the code below to the headsection of your HTML code, afterTVAis defined.

您可以尝试将下面的代码放在head您的 HTML 代码部分,TVA定义之后。

window.onkeydown = TVA.keyDown;

Or when using addEventListener():

或使用时addEventListener()

window.addEventListener('keydown', TVA.keyDown, false);

回答by raam86

You can attach listeners like this: you can pass a function or simply invoke an anonymous one in code.

您可以像这样附加侦听器:您可以传递一个函数或简单地在代码中调用一个匿名函数。

document.body.addEventListener('keydown',Main.onLoad);

Seems to work on stack overflow when passed to console.

传递到控制台时似乎可以解决堆栈溢出问题。