弃用
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> 元素。

HTML

<input>
<p id="log"></p>
					

JavaScript

const input = document.querySelector('input');
const log = document.getElementById('log');
input.onkeypress = logKey;
function logKey(e) {
  log.textContent += ` ${e.code}`;
}
					

结果

Filter keys with a regular expression

This example filters the characters typed into a form field using a regular expression .

HTML

<label>Enter numbers only:
  <input>
</label>
					

JavaScript

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;
					

结果

Capture the typing of a hidden word

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.
实时标准

浏览器兼容性

The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. 更新 GitHub 上的兼容性数据
桌面 移动
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet
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

图例

完整支持

完整支持

兼容性未知 ?

兼容性未知

Browser compatibility notes

  • 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).

另请参阅

元数据

  • 最后修改:
  1. GlobalEventHandlers
  2. 特性
    1. onabort
    2. onanimationcancel
    3. onanimationend
    4. onanimationiteration
    5. onauxclick
    6. onblur
    7. oncancel
    8. oncanplay
    9. oncanplaythrough
    10. onchange
    11. onclick
    12. onclose
    13. oncontextmenu
    14. oncuechange
    15. ondblclick
    16. ondurationchange
    17. onended
    18. onerror
    19. onfocus
    20. onformdata
    21. ongotpointercapture
    22. oninput
    23. oninvalid
    24. onkeydown
    25. onkeypress
    26. onkeyup
    27. onload
    28. onloadeddata
    29. onloadedmetadata
    30. onloadend
    31. onloadstart
    32. onlostpointercapture
    33. onmousedown
    34. onmouseenter
    35. onmouseleave
    36. onmousemove
    37. onmouseout
    38. onmouseover
    39. onmouseup
    40. onpause
    41. onplay
    42. onplaying
    43. onpointercancel
    44. onpointerdown
    45. onpointerenter
    46. onpointerleave
    47. onpointermove
    48. onpointerout
    49. onpointerover
    50. onpointerup
    51. onreset
    52. onresize
    53. onscroll
    54. onselect
    55. onselectionchange
    56. onselectstart
    57. onsubmit
    58. ontouchcancel
    59. ontouchstart
    60. ontransitioncancel
    61. ontransitionend
    62. onwheel
  3. 实现通过:
    1. Document
    2. HTMLElement
    3. SVGElement
    4. Window
    5. XULElement
  4. HTML DOM 相关页面
    1. BeforeUnloadEvent
    2. DOMStringMap
    3. ErrorEvent
    4. HTMLAnchorElement
    5. HTMLAreaElement
    6. HTMLAudioElement
    7. HTMLBRElement
    8. HTMLBaseElement
    9. HTMLBaseFontElement
    10. HTMLBodyElement
    11. HTMLButtonElement
    12. HTMLCanvasElement
    13. HTMLContentElement
    14. HTMLDListElement
    15. HTMLDataElement
    16. HTMLDataListElement
    17. HTMLDialogElement
    18. HTMLDivElement
    19. HTMLDocument
    20. HTMLElement
    21. HTMLEmbedElement
    22. HTMLFieldSetElement
    23. HTMLFormControlsCollection
    24. HTMLFormElement
    25. HTMLFrameSetElement
    26. HTMLHRElement
    27. HTMLHeadElement
    28. HTMLHeadingElement
    29. HTMLHtmlElement
    30. HTMLIFrameElement
    31. HTMLImageElement
    32. HTMLInputElement
    33. HTMLIsIndexElement
    34. HTMLKeygenElement
    35. HTMLLIElement
    36. HTMLLabelElement
    37. HTMLLegendElement
    38. HTMLLinkElement
    39. HTMLMapElement
    40. HTMLMediaElement
    41. HTMLMetaElement
    42. HTMLMeterElement
    43. HTMLModElement
    44. HTMLOListElement
    45. HTMLObjectElement
    46. HTMLOptGroupElement
    47. HTMLOptionElement
    48. HTMLOptionsCollection
    49. HTMLOutputElement
    50. HTMLParagraphElement
    51. HTMLParamElement
    52. HTMLPictureElement
    53. HTMLPreElement
    54. HTMLProgressElement
    55. HTMLQuoteElement
    56. HTMLScriptElement
    57. HTMLSelectElement
    58. HTMLShadowElement
    59. HTMLSourceElement
    60. HTMLSpanElement
    61. HTMLStyleElement
    62. HTMLTableCaptionElement
    63. HTMLTableCellElement
    64. HTMLTableColElement
    65. HTMLTableDataCellElement
    66. HTMLTableElement
    67. HTMLTableHeaderCellElement
    68. HTMLTableRowElement
    69. HTMLTableSectionElement
    70. HTMLTemplateElement
    71. HTMLTextAreaElement
    72. HTMLTimeElement
    73. HTMLTitleElement
    74. HTMLTrackElement
    75. HTMLUListElement
    76. HTMLUnknownElement
    77. HTMLVideoElement
    78. HashChangeEvent
    79. 历史
    80. ImageData
    81. 定位
    82. MessageChannel
    83. MessageEvent
    84. MessagePort
    85. Navigator
    86. NavigatorGeolocation
    87. NavigatorID
    88. NavigatorLanguage
    89. NavigatorOnLine
    90. NavigatorPlugins
    91. PageTransitionEvent
    92. Plugin
    93. PluginArray
    94. PopStateEvent
    95. PortCollection
    96. PromiseRejectionEvent
    97. RadioNodeList
    98. Transferable
    99. ValidityState
    100. Window
    101. WindowBase64
    102. WindowEventHandlers
    103. WindowTimers