假设您想要截取整个文档中的这些键:
document.onkeypress = function(evt) {
evt = evt || window.event;
var charCode = (typeof evt.which == "undefined") ? evt.keyCode : evt.which;
if (charCode) {
var charStr = String.fromCharCode(charCode);
if (charStr == ":") {
alert("Colon!");
} else if (charStr == ".") {
alert("Full stop!");
}
}
};
MarcelKorpel在评论中正确地指出,不使用
String.fromCharCode()
呼叫;这里有一个版本没有:
document.onkeypress = function(evt) {
evt = evt || window.event;
var charCode = (typeof evt.which == "undefined") ? evt.keyCode : evt.which;
if (charCode) {
if (charCode == 58) {
alert("Colon!");
} else if (charCode == 46) {
alert("Full stop!");
}
}
};