有几种方法可以解决这个问题;Vanilla JavaScript可以很好地做到这一点:
function code(e) {
e = e || window.event;
return(e.keyCode || e.which);
}
window.onload = function(){
document.onkeypress = function(e){
var key = code(e);
};
};
或更有条理的处理方式:
(function(d){
var modern = (d.addEventListener), event = function(obj, evt, fn){
if(modern) {
obj.addEventListener(evt, fn, false);
} else {
obj.attachEvent("on" + evt, fn);
}
}, code = function(e){
e = e || window.event;
return(e.keyCode || e.which);
}, init = function(){
event(d, "keypress", function(e){
var key = code(e);
});
};
if(modern) {
d.addEventListener("DOMContentLoaded", init, false);
} else {
d.attachEvent("onreadystatechange", function(){
if(d.readyState === "complete") {
init();
}
});
}
})(document);