JavaScript 监听器,“按键”没有检测到退格键?

发布于 2024-10-15 06:25:48 字数 183 浏览 3 评论 0原文

我正在使用 keypress 监听器,例如......

addEventListener("keypress", function(event){

}

但是,这似乎没有检测到删除文本的退格键......

是否有不同的监听器可以用来检测这个?

I'm using a keypress listener eg..

addEventListener("keypress", function(event){

}

However, this doesn't seem to detect a backspace which erases text...

Is there a different listener I can use to detect this?

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

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

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

别低头,皇冠会掉 2024-10-22 06:25:48

KeyPress 事件仅针对字符(可打印)键调用,KeyDown 事件针对所有不可打印键引发,例如 ControlShiftAlt、< kbd>BackSpace 等

更新:

按下某个键时会触发 keypress 事件,并且该键通常会产生一个字符值

参考

KeyPress event is invoked only for character (printable) keys, KeyDown event is raised for all including nonprintable such as Control, Shift, Alt, BackSpace, etc.

UPDATE:

The keypress event is fired when a key is pressed down and that key normally produces a character value

Reference.

递刀给你 2024-10-22 06:25:48

尝试使用 keydown 而不是 keypress

键盘事件按以下顺序发生:keydownkeyupkeypress

退格键的问题可能是,浏览器将导航回 >keyup,因此您的页面将看不到 keypress 事件。

Try keydown instead of keypress.

The keyboard events occur in this order: keydown, keyup, keypress

The problem with backspace probably is, that the browser will navigate back on keyup and thus your page will not see the keypress event.

萌辣 2024-10-22 06:25:48

不同浏览器的 keypress 事件可能有所不同。

我创建了一个 Jsfiddle 来比较 Chrome 和 Firefox 上的键盘事件(使用 JQuery 快捷键)。根据您使用的浏览器,是否会触发 keypress 事件 - 在 Firefox 上,退格键将触发 keydown/keypress/keyup,但仅触发 keydown/keyup 在 Chrome 上。

触发单键单击事件

在 Chrome 上

  • 当浏览器注册键盘输入(keypress 被触发)时,
  • keydown/keyup 如果没有键盘输入(测试使用alt、shift、退格键、箭头键)

  • keydown仅适用于选项卡?

在 Firefox 上

  • keydown/keypress/keyup 当浏览器注册键盘输入时,也用于退格键、箭头键、Tab 键(所以这里 keypress即使没有输入也会触发)

  • keydown/keyup 用于 alt、shift


这应该不足为奇,因为根据https://api.jquery.com/keypress/

注意:由于任何官方均未涵盖按键事件
规范,使用时遇到的实际行为可能
因浏览器、浏览器版本和平台的不同而有所不同。

W3C 不推荐使用按键事件类型 (http://www .w3.org/TR/DOM-Level-3-Events/#event-type-keypress)

本规范中定义了按键事件类型,以供参考
和完整性,但本规范不赞成使用此
事件类型。在编辑上下文中时,作者可以订阅
改为 beforeinput 事件。


最后,要回答您的问题,您应该使用 keyupkeydown 来检测 Firefox 和 Chrome 中的退格键。


在这里尝试一下:

$(".inputTxt").bind("keypress keyup keydown", function (event) {
    var evtType = event.type;
    var eWhich = event.which;
    var echarCode = event.charCode;
    var ekeyCode = event.keyCode;

    switch (evtType) {
        case 'keypress':
            $("#log").html($("#log").html() + "<b>" + evtType + "</b>" + " keycode: " + ekeyCode + " charcode: " + echarCode + " which: " + eWhich + "<br>");
            break;
        case 'keyup':
            $("#log").html($("#log").html() + "<b>" + evtType + "</b>" + " keycode: " + ekeyCode + " charcode: " + echarCode + " which: " + eWhich + "<p>");
            break;
        case 'keydown':
            $("#log").html($("#log").html() + "<b>" + evtType + "</b>" + " keycode: " + ekeyCode + " charcode: " + echarCode + " which: " + eWhich + "<br>");
            break;
        default:
            break;
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input class="inputTxt" type="text" />
<div id="log"></div>

The keypress event might be different across browsers.

I created a Jsfiddle to compare keyboard events (using the JQuery shortcuts) on Chrome and Firefox. Depending on the browser you're using a keypress event will be triggered or not -- backspace will trigger keydown/keypress/keyup on Firefox but only keydown/keyup on Chrome.

Single keyclick events triggered

on Chrome

  • keydown/keypress/keyup when browser registers a keyboard input (keypress is fired)

  • keydown/keyup if no keyboard input (tested with alt, shift, backspace, arrow keys)

  • keydown only for tab?

on Firefox

  • keydown/keypress/keyup when browser registers a keyboard input but also for backspace, arrow keys, tab (so here keypress is fired even with no input)

  • keydown/keyup for alt, shift


This shouldn't be surprising because according to https://api.jquery.com/keypress/:

Note: as the keypress event isn't covered by any official
specification, the actual behavior encountered when using it may
differ across browsers, browser versions, and platforms.

The use of the keypress event type is deprecated by W3C (http://www.w3.org/TR/DOM-Level-3-Events/#event-type-keypress)

The keypress event type is defined in this specification for reference
and completeness, but this specification deprecates the use of this
event type. When in editing contexts, authors can subscribe to the
beforeinput event instead.


Finally, to answer your question, you should use keyup or keydown to detect a backspace across Firefox and Chrome.


Try it out on here:

$(".inputTxt").bind("keypress keyup keydown", function (event) {
    var evtType = event.type;
    var eWhich = event.which;
    var echarCode = event.charCode;
    var ekeyCode = event.keyCode;

    switch (evtType) {
        case 'keypress':
            $("#log").html($("#log").html() + "<b>" + evtType + "</b>" + " keycode: " + ekeyCode + " charcode: " + echarCode + " which: " + eWhich + "<br>");
            break;
        case 'keyup':
            $("#log").html($("#log").html() + "<b>" + evtType + "</b>" + " keycode: " + ekeyCode + " charcode: " + echarCode + " which: " + eWhich + "<p>");
            break;
        case 'keydown':
            $("#log").html($("#log").html() + "<b>" + evtType + "</b>" + " keycode: " + ekeyCode + " charcode: " + echarCode + " which: " + eWhich + "<br>");
            break;
        default:
            break;
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input class="inputTxt" type="text" />
<div id="log"></div>

情绪少女 2024-10-22 06:25:48

我写的东西,以防有人遇到人们在认为自己处于表单字段中时按退格键的问题

window.addEventListener("keydown", function(e){
    /*
     * keyCode: 8
     * keyIdentifier: "U+0008"
    */
    if(e.keyCode === 8 && document.activeElement !== 'text') {
        e.preventDefault();
        alert('Prevent page from going back');
    }
});

Something I wrote up incase anyone comes across an issue with people hitting backspace while thinking they are in a form field

window.addEventListener("keydown", function(e){
    /*
     * keyCode: 8
     * keyIdentifier: "U+0008"
    */
    if(e.keyCode === 8 && document.activeElement !== 'text') {
        e.preventDefault();
        alert('Prevent page from going back');
    }
});
指尖凝香 2024-10-22 06:25:48

event.key === "Backspace"

更新且更简洁:使用 event.key。不再有任意数字代码!

note.addEventListener('keydown', function(event) {
    const key = event.key; // const {key} = event; ES6+
    if (key === "Backspace") {
        // Do something
    }
});

Mozilla 文档

支持的浏览器

event.key === "Backspace"

More recent and much cleaner: use event.key. No more arbitrary number codes!

note.addEventListener('keydown', function(event) {
    const key = event.key; // const {key} = event; ES6+
    if (key === "Backspace") {
        // Do something
    }
});

Mozilla Docs

Supported Browsers

想你的星星会说话 2024-10-22 06:25:48

我的数字控制:

function CheckNumeric(event) {
    var _key = (window.Event) ? event.which : event.keyCode;
    if (_key > 95 && _key < 106) {
        return true;
    }
    else if (_key > 47 && _key < 58) {
        return true;
    }
    else {
        return false;
    }
}

<input type="text" onkeydown="return CheckNumerick(event);" />

试试

BackSpace键代码是8

My numeric control:

function CheckNumeric(event) {
    var _key = (window.Event) ? event.which : event.keyCode;
    if (_key > 95 && _key < 106) {
        return true;
    }
    else if (_key > 47 && _key < 58) {
        return true;
    }
    else {
        return false;
    }
}

<input type="text" onkeydown="return CheckNumerick(event);" />

try it

BackSpace key code is 8

帅的被狗咬 2024-10-22 06:25:48

请改用 keyup / keydown / beforeinput 事件之一。

基于参考,按键已被弃用并且不更长推荐。

当按键产生字符值时,将触发按键事件
被按下。产生字符值的键的示例是
字母、数字和标点符号键。不支持的键示例
产生字符值的是修饰键,例如 Alt、Shift、Ctrl、
或元。

如果您使用“beforeinput”,请注意它的 浏览器兼容性。 “beforeinput”和其他两个之间的区别在于,“beforeinput”在输入值即将更改时被触发,因此对于无法更改输入值的字符,它不会被触发(例如shift,ctr,alt)。

我遇到了同样的问题,通过使用 keyup 解决了。

Use one of keyup / keydown / beforeinput events instead.

based on this reference, keypress is deprecated and no longer recommended.

The keypress event is fired when a key that produces a character value
is pressed down. Examples of keys that produce a character value are
alphabetic, numeric, and punctuation keys. Examples of keys that don't
produce a character value are modifier keys such as Alt, Shift, Ctrl,
or Meta.

if you use "beforeinput" be careful about it's Browser compatibility. the difference between "beforeinput" and the other two is that "beforeinput" is fired when input value is about to changed, so with characters that can't change the input value, it is not fired (e.g shift, ctr ,alt).

I had the same problem and by using keyup it was solved.

姜生凉生 2024-10-22 06:25:48

我正在尝试 keydown 并且 Backspace 没有被捕获。切换到 keyup 对我有用。

addEventListener("keyup", function(event){

}

作为参考,以防有人使用 .on 来动态生成内容。

$("body").on( "keyup", ".my-element", function(evt) {
      // Do something
});

I was trying keydown and Backspace was not being captured. Switching to keyup worked for me.

addEventListener("keyup", function(event){

}

For reference, in case someone is using with .on for dynamically generated content.

$("body").on( "keyup", ".my-element", function(evt) {
      // Do something
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文