GlobalEventHandlers.onkeypress
onkeypress 属性用来获取或设置当前元素的keypress事件的事件处理函数.
语法
element.onkeypress = event handling code
备注
当用户在键盘上按下任意键时,应当会触发 keypress 事件。然则有些浏览器不会触发某些键的 kerpress 事件。
浏览器不兼容性
Webkit-based 浏览器(如 Google Chrome 及 Safari)不会触发方向键的 keypress 事件。
Firefox 不会触发如 SHIFT 键等修改键的 keypress 事件。
示例
示例1:通过正则表达式在表单域中过滤数字
下例演示了 onkeypress
事件在一个文本输入框内的用法——将数字输入到表单时过滤输入的内容:
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Example</title>
<script type="text/javascript">
function numbersOnly(oToCheckField, oKeyEvent) {
return oKeyEvent.charCode === 0 || /\d/.test(String.fromCharCode(oKeyEvent.charCode));
}
</script>
</head>
<body>
<form name="myForm">
<p>这个文本框只能输入数字(译者注:不用中文输入法的前提下):
<input type="text" name="myInput" onkeypress="return numbersOnly(this, event);" onpaste="return false;" /></p>
</form>
</body>
</html>
示例2:捕获隐藏单词的输入
以下示例将在用户在页面的任何位置键入单词“exit”后执行某些操作。
Note: A more complete framework for capturing the typing of hidden words is available on GitHub.
/* Type the word "exit" in any point of your page... */
(function () {
var sSecret = /* chose your hidden word...: */ "exit", nOffset = 0;
document.onkeypress = function (oPEvt) {
var oEvent = oPEvt || window.event, nChr = oEvent.charCode, sNodeType = oEvent.target.nodeName.toUpperCase();
if (nChr === 0 || oEvent.target.contentEditable.toUpperCase() === "TRUE" || sNodeType === "TEXTAREA" || sNodeType === "INPUT" && oEvent.target.type.toUpperCase() === "TEXT") { return true; }
if (nChr !== sSecret.charCodeAt(nOffset)) {
nOffset = nChr === sSecret.charCodeAt(0) ? 1 : 0;
} else if (nOffset < sSecret.length - 1) {
nOffset++;
} else {
nOffset = 0;
/* do something here... */
alert("Yesss!!!");
location.assign("http://developer.mozilla.org/");
}
return true;
};
})();
规范
Specification | Status | Comment |
---|---|---|
HTML Living Standard onkeypress |
Living Standard |
Browser compatibility
BCD tables only load in the browser