我有以下代码,当用户在输入字段上时检测任何按键:
// Trigger clicking the submit button if the user ever presses enter
$('.Textinput').on('keypress', function(e) {
if(e.which == 13){//Enter key pressed
$('#payment-form').click();
}
});
但是,如果曾经页面上存在按键,无论光标/事件元素位于何处,我将如何做同样的事情?
最佳答案
使用文档,在下面的示例中,它从反射(reflect)到计数器的整个文档中捕获按键事件。这个解决方案适用于我的 chrome。
<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
i = 0;
$(document).ready(function() {
$(document).keypress(function() {
$("span").text(i += 1);
});
});
</script>
</head>
<body>
Type anything on page or Enter your name:
<input type="text">
<p>
Keypresses: <span>0</span>
</p>
</body>
</html>
关于javascript - 如何检测javascript中的任何按键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52884411/