keydown EventListener in IE7
I've written this code inside the HEAD tags of my HTML page. It works fine in Firefox, Chrome and Safari, but doesn't in IE7. I would like to know how to fix it.
<script type="text/javascript">
if ( window.addEventListener ) {
window.addEventListener("keydown", functio开发者_StackOverflow中文版n(e) {
alert(e.keyCode);
}, true);
}
</script>
Microsoft has implemented their own way of doing this called attachEvent
. You can read more about this over at quirksmode.org: http://www.quirksmode.org/js/events_advanced.html
You're screwed: you're using event capturing (passing true
as the last parameter to addEventListener
). IE has no such equivalent, in any version, including IE8 in IE8 mode.
Is there a reason you must use event capturing rather that event bubbling here? IOW, pass false
as your last parameter? Then, you'd be able to port this (somewhat) to use IE's attachEvent
proprietary method, or use a library (as others have suggested and added links for).
There is no window.addEventListener
in IE, you need to use attachEvent
. There's good documentation on events here, or you could switch to using a library that abstracts away browser differences.
Try:
window.attachEvent
More fully:
//set page event handlers
if (window.attachEvent) {
//IE and Opera
window.attachEvent("keydown", "");
} else if (window.addEventListener) {
// IE 6
window.addEventListener("keydown", "");
} else {
//FireFox
document.addEventListener("keydown", "");
}
精彩评论