[英]How to add onkeydown to body?
In my index.html I have this code. 在我的index.html中,我有这个代码。 I would need to add onkeydown
event to that body in Main.onLoad(). 我需要在Main.onLoad()中向该主体添加onkeydown
事件。
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();"
>
In a Javascript block, try to use window.onkeydown
( MDN ). 在Javascript块中,尝试使用window.onkeydown
( MDN )。
You can also use document.onkeydown
and document.body.onkeydown
. 您还可以使用document.onkeydown
和document.body.onkeydown
。
Here is an example for you: 这是一个例子:
document.body.onkeydown = function(e){
alert(String.fromCharCode(e.keyCode)+" --> "+e.keyCode);
};
The code above can be put in any valid JavaScript block (such as Main.onLoad()
function). 上面的代码可以放在任何有效的JavaScript块中(例如Main.onLoad()
函数)。
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. 传递给控制台时似乎可以处理堆栈溢出。
Usually onkeydown
can be attached to the elements which can receive focus. 通常onkeydown
可以附加到可以获得焦点的元素上。 In some browsers you can gain focus to the document.body
, but you can't rely on that. 在某些浏览器中,您可以专注于document.body
,但您不能依赖它。 window
is one of those elements which can gain the focus. window
是可以获得焦点的元素之一。
You can try to put the code below to the head
section of your HTML code, after TVA
is defined. 在定义TVA
之后 ,您可以尝试将下面的代码放在HTML代码的head
部分。
window.onkeydown = TVA.keyDown;
Or when using addEventListener()
: 或者在使用addEventListener()
:
window.addEventListener('keydown', TVA.keyDown, false);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.