javascript 如何在 IE8 中使用特定键码生成 keyup 事件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7518664/
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
How can I generate a keyup event with a specific keycode in IE8?
提问by ktusznio
I need to generate keyup events in IE 8 using native DOM functions (no jQuery). The following code generates, fires, and receives the event, but the keyCode is always 0. How do I properly pass the keyCode?
我需要使用本机 DOM 函数(无 jQuery)在 IE 8 中生成 keyup 事件。以下代码生成、触发和接收事件,但 keyCode 始终为 0。如何正确传递 keyCode?
<form><input id="me" type="submit" /></form>
<script type="text/javascript">
var me = document.getElementById("me");
me.attachEvent("onkeyup", function(e) {
alert(e.keyCode); // => 0
});
document.getElementById("me").fireEvent('onkeyup', 13);
</script>
回答by ktusznio
Figured it out. The solution is to create an event object, assign the keycode, and fire it from the node.
弄清楚了。解决方案是创建一个事件对象,分配键码,然后从节点触发它。
var e = document.createEventObject("KeyboardEvent");
e.keyCode = keyCode;
node.fireEvent("onkeyup", e);
回答by Niet the Dark Absol
e = e || window.event;
keycode = e.keyCode || e.which;
That will make events work in all browsers.
Also, I prefer to use me.onkeyup = function(e) { ... }
, but that' just personal preference (I know the drawbacks of this method, but I have clever ways to work around them)
这将使事件在所有浏览器中工作。此外,我更喜欢使用me.onkeyup = function(e) { ... }
,但这只是个人喜好(我知道这种方法的缺点,但我有巧妙的方法来解决它们)