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

Sự kiện bàn phím (Key Events) trong JavaScript

Tổng quan

Key Events xử lý tương tác bàn phím. Có 3 sự kiện chính theo thứ tự xảy ra:

Sự kiệnKích hoạt khiLưu ý
keydownPhím được nhấn xuốngLặp lại nếu giữ phím (key repeat)
keypressPhím ký tự được nhấn (đã lỗi thời)Deprecated - không dùng cho dự án mới
keyupPhím được nhả raChỉ kích hoạt 1 lần

Lưu ý: keypress đã bị loại khỏi tiêu chuẩn web. Nên dùng keydown hoặc beforeinput thay thế.

Đối tượng KeyboardEvent

Thuộc tính quan trọng:

  • key: Giá trị ký tự của phím (ví dụ: "Enter", "a", "Shift")
  • code: Vị trí vật lý của phím (ví dụ: "KeyA", "Enter", "ShiftLeft")
  • ctrlKey, shiftKey, altKey, metaKey: Trạng thái phím modifier

Ví dụ: Theo dõi các sự kiện phím

<!DOCTYPE html>
<html lang="vi">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Key Events</title>
    <style>
        body { font-family: 'Segoe UI', sans-serif; padding: 20px; }
        .result { font-size: 16px; color: #6a1b9a; font-weight: 500; margin-top: 20px; padding: 15px; background: #f3e5f5; border-radius: 4px; min-height: 100px; white-space: pre-wrap; }
        h3 { color: #555; }
    </style>
</head>
<body>
    <h1>Key Events trong JavaScript</h1>
    <div class="result" id="result">Nhấn phím bất kỳ...</div>
    <h3>Nhấn hoặc giữ phím để xem sự kiện kích hoạt</h3>

    <script>
        const resEle = document.getElementById('result');
        let log = [];

        document.addEventListener('keydown', (e) => {
            log.unshift(`⬇ keydown: key="${e.key}" code="${e.code}" ${e.repeat ? '(repeat)' : ''}`);
            if (log.length > 10) log.pop();
            resEle.textContent = log.join('\n');
        });

        document.addEventListener('keyup', (e) => {
            log.unshift(`⬆ keyup: key="${e.key}" code="${e.code}"`);
            if (log.length > 10) log.pop();
            resEle.textContent = log.join('\n');
        });

        // keypress đã deprecated - không khuyến khích sử dụng
        document.addEventListener('keypress', (e) => {
            log.unshift(`🔤 keypress: key="${e.key}" (DEPRECATED)`);
            if (log.length > 10) log.pop();
            resEle.textContent = log.join('\n');
        });
    </script>
</body>
</html>

Ứng dụng thực tế

1. Phím tắt (Shortcuts)

document.addEventListener('keydown', (e) => {
    if (e.ctrlKey && e.key === 's') {
        e.preventDefault(); // Ngăn Ctrl+S mặc định
        saveDocument();
    }
    if (e.key === 'Escape') {
        closeModal();
    }
});

2. Xử lý nhập liệu (Form validation)

input.addEventListener('keydown', (e) => {
    // Chỉ cho phép số
    if (!/[\d]/.test(e.key) && !['Backspace', 'Delete', 'ArrowLeft', 'ArrowRight', 'Tab'].includes(e.key)) {
        e.preventDefault();
    }
});

3. Game điều khiển bằng phím

const keys = {};
window.addEventListener('keydown', e => keys[e.code] = true);
window.addEventListener('keyup', e => keys[e.code] = false);

function gameLoop() {
    if (keys['ArrowLeft']) player.x -= 5;
    if (keys['ArrowRight']) player.x += 5;
    requestAnimationFrame(gameLoop);
}