开发者

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). The following code generates, fires, and receives the event, but the keyCode is always 0. How do I properly pass the 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)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜