Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Cách mô phỏng sự kiện keypress trong JavaScript

Để mô phỏng sự kiện nhấn phím (keypress), bạn sử dụng event handler. Ví dụ dưới đây dùng jQuery để trigger sự kiện keypress ảo.

Ví dụ

<!DOCTYPE html>
<html>
<head>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function() {
            $('body').keypress(function(e) {
                alert(String.fromCharCode(e.which));
            });
            $.fn.simulateKeyPress = function(character) {
                $(this).trigger({
                    type: 'keypress',
                    which: character.charCodeAt(0)
                });
            };
            setTimeout(function() {
                $('body').simulateKeyPress('z');
            }, 2000);
        });
    </script>
</head>
<body>
    <p>Nhấn bất kỳ phím nào (hoặc chờ 2 giây để xem mô phỏng 'z')</p>
</body>
</html>

Lưu ý: Cách này chỉ hoạt động với jQuery. Với vanilla JS, dùng new KeyboardEvent('keypress', {key: 'z'}) và dispatchEvent().