弃用
This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the
兼容性表格
at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.
onkeypress
特性为
GlobalEventHandlers
混合
EventHandler
处理
keypress
事件。
keypress
event
should
fire when the user presses a key on the keyboard. However, in practice browsers do not fire
keypress
events for certain keys.
onkeypress
event handler has been deprecated. You may want to use
onkeydown
代替。
target.onkeypress = functionRef;
functionRef
is a function name or a
函数表达式
. The function receives a
KeyboardEvent
object as its sole argument.
This example logs the
KeyboardEvent.code
value whenever you press a key inside the
<input>
元素。
<input> <p id="log"></p>
const input = document.querySelector('input');
const log = document.getElementById('log');
input.onkeypress = logKey;
function logKey(e) {
log.textContent += ` ${e.code}`;
}
This example filters the characters typed into a form field using a regular expression .
<label>Enter numbers only: <input> </label>
function numbersOnly(event) {
return event.charCode === 0 || /\d/.test(String.fromCharCode(event.charCode));
}
const input = document.querySelector('input');
input.onkeypress = numbersOnly;
// Prevent pasting (since pasted content might include non-number characters)
input.onpaste = event => false;
The following JavaScript function will do something after the user types the word "exit" in any point of a page.
/* Type the word "exit" in any point of your page... */
(function () {
const sSecret = /* Choose your hidden word...: */ "exit";
let nOffset = 0;
document.onkeypress = function(oPEvt) {
let 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("https://developer.mozilla.org/");
}
return true;
};
})();
注意: A more complete framework for capturing the typing of hidden words is available on GitHub .
| 规范 | 状态 | 注释 |
|---|---|---|
|
HTML 实时标准
The definition of 'onkeypress' in that specification. |
实时标准 |
| 桌面 | 移动 | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
onkeypress
|
Chrome Yes | Edge ≤18 | Firefox Yes | IE ? | Opera ? | Safari ? | WebView Android Yes | Chrome Android Yes | Firefox Android Yes | Opera Android ? | Safari iOS ? | Samsung Internet Android Yes |
完整支持
兼容性未知
keypress
event is no longer fired for
non-printable keys
(见
bug 968056
for Firefox 65's implementation of this), except for the
Enter
key, and the
Shift
+
Enter
and
Ctrl
+
Enter
key combinations (these were kept for cross-browser compatibility purposes).
keypress
event
GlobalEventHandlers
onabort
onanimationcancel
onanimationend
onanimationiteration
onauxclick
onblur
oncancel
oncanplay
oncanplaythrough
onchange
onclick
onclose
oncontextmenu
oncuechange
ondblclick
ondurationchange
onended
onerror
onfocus
onformdata
ongotpointercapture
oninput
oninvalid
onkeydown
onkeypress
onkeyup
onload
onloadeddata
onloadedmetadata
onloadend
onloadstart
onlostpointercapture
onmousedown
onmouseenter
onmouseleave
onmousemove
onmouseout
onmouseover
onmouseup
onpause
onplay
onplaying
onpointercancel
onpointerdown
onpointerenter
onpointerleave
onpointermove
onpointerout
onpointerover
onpointerup
onreset
onresize
onscroll
onselect
onselectionchange
onselectstart
onsubmit
ontouchcancel
ontouchstart
ontransitioncancel
ontransitionend
onwheel
BeforeUnloadEvent
DOMStringMap
ErrorEvent
HTMLAnchorElement
HTMLAreaElement
HTMLAudioElement
HTMLBRElement
HTMLBaseElement
HTMLBaseFontElement
HTMLBodyElement
HTMLButtonElement
HTMLCanvasElement
HTMLContentElement
HTMLDListElement
HTMLDataElement
HTMLDataListElement
HTMLDialogElement
HTMLDivElement
HTMLDocument
HTMLElement
HTMLEmbedElement
HTMLFieldSetElement
HTMLFormControlsCollection
HTMLFormElement
HTMLFrameSetElement
HTMLHRElement
HTMLHeadElement
HTMLHeadingElement
HTMLHtmlElement
HTMLIFrameElement
HTMLImageElement
HTMLInputElement
HTMLIsIndexElement
HTMLKeygenElement
HTMLLIElement
HTMLLabelElement
HTMLLegendElement
HTMLLinkElement
HTMLMapElement
HTMLMediaElement
HTMLMetaElement
HTMLMeterElement
HTMLModElement
HTMLOListElement
HTMLObjectElement
HTMLOptGroupElement
HTMLOptionElement
HTMLOptionsCollection
HTMLOutputElement
HTMLParagraphElement
HTMLParamElement
HTMLPictureElement
HTMLPreElement
HTMLProgressElement
HTMLQuoteElement
HTMLScriptElement
HTMLSelectElement
HTMLShadowElement
HTMLSourceElement
HTMLSpanElement
HTMLStyleElement
HTMLTableCaptionElement
HTMLTableCellElement
HTMLTableColElement
HTMLTableDataCellElement
HTMLTableElement
HTMLTableHeaderCellElement
HTMLTableRowElement
HTMLTableSectionElement
HTMLTemplateElement
HTMLTextAreaElement
HTMLTimeElement
HTMLTitleElement
HTMLTrackElement
HTMLUListElement
HTMLUnknownElement
HTMLVideoElement
HashChangeEvent
历史
ImageData
定位
MessageChannel
MessageEvent
MessagePort
Navigator
NavigatorGeolocation
NavigatorID
NavigatorLanguage
NavigatorOnLine
NavigatorPlugins
PageTransitionEvent
Plugin
PluginArray
PopStateEvent
PortCollection
PromiseRejectionEvent
RadioNodeList
Transferable
ValidityState
Window
WindowBase64
WindowEventHandlers
WindowTimers