简体   繁体   English

如何在IE8中生成具有特定键码的键盘事件?

[英]How can I generate a keyup event with a specific keycode in IE8?

I need to generate keyup events in IE 8 using native DOM functions (no jQuery). 我需要使用本机DOM函数(没有jQuery)在IE 8中生成keyup事件。 The following code generates, fires, and receives the event, but the keyCode is always 0. How do I properly pass the keyCode? 以下代码生成,触发并接收事件,但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>

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);
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) { ... } ,但这只是个人偏好(我知道这种方法的缺点,但我有聪明的方法来解决它们)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM