gpt4 book ai didi

javascript - Tabbable DIV 上的空格键或 Enter 键 : Some browsers don't intercept Keypress

转载 作者:行者123 更新时间:2023-12-01 01:19:07 25 4
gpt4 key购买 nike

一旦获得焦点,我需要拦截 Tabbable DIV 上的 Enter 或 Space(13 或 32) 按键。

我看到以下内容:

  1. Chrome 两者都支持。

  2. Firefox 不支持空格

  3. IE11不支持Enter

可以依次用每个浏览器打开以下代码片段以查看差异:

$('#buttondiv').keypress(function (e) {

// First log which key was pressed
console.log(e.keyCode);

if (e.keyCode == 13 || e.keyCode == 32) {
alert('Intercepted Enter or Space');
}
});
#buttondiv {
border: 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>

<button id="buttonfocus" onclick="$('#buttondiv').focus()">
Click here to focus DIV first
</button>

<div id="buttondiv" tabindex="0">
Press Enter or Space on DIV after focusing
</div>

此外,如果有兴趣,JSFiddle(但 JSFiddle 不会在 IE 中打开): http://jsfiddle.net/v406agb1/

最佳答案

您应该使用keydown而不是keypress。这就是official documentation says :

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.

This method is a shortcut for .on( "keypress", handler ) in the first two variations, and .trigger( "keypress" ) in the third.

The keypress event is sent to an element when the browser registers keyboard input. This is similar to the keydown event, except that modifier and non-printing keys such as Shift, Esc, and delete trigger keydown events but not keypress events. Other differences between the two events may arise depending on platform and browser.

$('#buttondiv').keydown(function (e) {

// First log which key was pressed
console.log(e.keyCode);

if (e.keyCode == 13 || e.keyCode == 32) {
alert('Intercepted Enter or Space');
}
});
#buttondiv {
border: 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>

<button id="buttonfocus" onclick="$('#buttondiv').focus()">
Click here to focus DIV first
</button>

<div id="buttondiv" tabindex="0">
Press Enter or Space on DIV after focusing
</div>

关于javascript - Tabbable DIV 上的空格键或 Enter 键 : Some browsers don't intercept Keypress,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54410536/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com