首页 > 解决方案 > 如何检测javascript中的任何kepress

问题描述

当用户在输入字段上时,我有以下代码检测任何按键:

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

但是,如果页面上有按键,无论光标/活动元素在哪里,我将如何做同样的事情?

标签: javascriptjquery

解决方案


使用文档,在以下示例中,它从整个文档中捕获反映到计数器的按键事件。这个解决方案在 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>

推荐阅读