我正在制作一个 Chrome 扩展程序,有时会暂时阻止所有键盘输入到达网页(因为扩展程序的处理程序使用它捕获的键盘输入执行自己的任务)。该扩展程序可以很好地监听所有这些输入。
但是,一些键盘输入仍然可以通过网页进行!具体来说,使用 Alt 修饰键的某些键盘输入会到达网页。我已经用这段代码复制了这个问题:
$(window).get(0).addEventListener("keypress",
function(e){
e.stopPropagation();
e.preventDefault();
}, true);
您可以与这个jsfiddle中的代码进行交互:https://jsfiddle.net/Sophtware/5ucefew2/
有人可以帮我弄清楚为什么会发生这种情况以及如何解决它吗?
编辑 #1:我发现通过 PreventDefault 调用传入的符号是重音符号或其他“组合字符”(如 ´、ˆ、 ¡)。事实上,一旦输入了组合字符,下一个输入的字符也将始终无法被阻止。
最佳答案
首先,您的 Fiddle 中没有加载 jQuery。
其次,您需要使用 keydown
事件,而不是 keypress
因为当按键不产生可见时 keypress
不会触发字符被按下。这就是为什么您发现某些 Angular 色可以使用它而其他 Angular 色则不能。
第三,您的事件绑定(bind)代码并未真正正确编写。当 jQuery 返回仅包含一项的包装集时,无需使用 get(0)
。由于只有一个窗口
或文档
,因此不需要该代码。
此外,您可以明确检查是否按下了 ALT 键。
最后,请不要将您的代码发布到第三方网站,因为这些链接可能会随着时间的推移而损坏。相反,请在此处发布您的代码片段。
查看内嵌评论:
// Set the event on the document, but then test for the input element when it happens
$(document).on("keydown", "input[type='text']", function(e){
// Check the event for the ALT key press
console.log("Keystroke cancelled!");
e.preventDefault();
e.stopPropagation();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3>
Type in Alt + 'e', Alt + 'i', or other Alt combinations! They get typed in even though they're not supposed to!
</h3>
<p>
Strangely, Alt+j and Alt+k cannot be written more than once in a row and act strange in general.
If you type in Alt + e and then a regular letter key press, the letter gets typed! ??????
</p>
<input type="text">
关于javascript - PreventDefault 不阻止使用 Alt 修饰符的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45176190/