GlobalEventHandlers.onkeypress - Web APIs 编辑

Deprecated

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 compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

The onkeypress property of the GlobalEventHandlers mixin is an EventHandler that processes keypress events.

The 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.

The onkeypress event handler has been deprecated. You may want to use onkeydown instead.

Syntax

target.onkeypress = functionRef;

Value

functionRef is a function name or a function expression. The function receives a KeyboardEvent object as its sole argument.

Examples

Basic example

This example logs the KeyboardEvent.code value whenever you press a key inside the <input> element.

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}`;
}

Result

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;

Result

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("/wiki/");
    }

    return true;
  };
})();

Note: A more complete framework for capturing the typing of hidden words is available on GitHub.

Specifications

SpecificationStatusComment
HTML Living Standard
The definition of 'onkeypress' in that specification.
Living Standard 

Browser compatibility

BCD tables only load in the browser

  • The keypress event is no longer fired for non-printable keys (see 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).

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:41 次

字数:7660

最后编辑:6 年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文