Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

บทบาทของ Keyboard Event ctrlKey Property ใน JavaScript

event.ctrlKey เป็น Property ของ KeyboardEvent (และ MouseEvent) ที่บอกว่า ปุ่ม Ctrl ถูกกดค้างอยู่หรือไม่ ในขณะที่ Event ถูก Trigger (true = กดอยู่, false = ไม่ได้กด)

ตัวอย่าง: ตรวจจับ Ctrl + Key

<!DOCTYPE html>
<html>
<body>
  <input type="text" id="input" placeholder="ลองกด Ctrl + S, Ctrl+Enter..." style="width: 300px; padding: 8px;" />
  <div id="log" style="margin-top: 10px; font-family: monospace; white-space: pre-wrap;"></div>

  <script>
    const input = document.getElementById('input');
    const log = document.getElementById('log');

    input.addEventListener('keydown', (e) => {
      const key = e.key;
      const ctrl = e.ctrlKey;
      const shift = e.shiftKey;
      const alt = e.altKey;
      const meta = e.metaKey; // Cmd (Mac) / Win Key

      let combo = [];
      if (ctrl) combo.push('Ctrl');
      if (shift) combo.push('Shift');
      if (alt) combo.push('Alt');
      if (meta) combo.push('Meta');
      combo.push(key);

      log.textContent = `Keydown: ${combo.join(' + ')} | ctrlKey: ${ctrl}`;

      // ตัวอย่าง Shortcut: Ctrl+S (Save), Ctrl+Enter (Submit)
      if (ctrl && key === 's') {
        e.preventDefault(); // ป้องกัน Save Dialog ของ Browser
        log.textContent += '\n→ Triggered: Save Action (Ctrl+S)';
      }
      if (ctrl && key === 'Enter') {
        log.textContent += '\n→ Triggered: Submit (Ctrl+Enter)';
      }
    });
  </script>
</body>
</html>

คุณสมบัติ Modifier Keys ทั้ง 4 (KeyboardEvent & MouseEvent)

PropertyKeyคำอธิบาย
ctrlKeyControl (Ctrl)Windows/Linux: Ctrl, Mac: Control (⌃)
shiftKeyShiftShift Key ทั้งซ้าย/ขวา
altKeyAlt / OptionWindows: Alt, Mac: Option (⌥)
metaKeyMeta / Command / WindowsMac: Command (⌘), Windows: Win Key, Linux: Super

การใช้งานทั่วไป (Common Use Cases)

1. Keyboard Shortcuts (Hotkeys)

document.addEventListener('keydown', (e) => {
  // Save: Ctrl+S (Win/Linux) / Cmd+S (Mac)
  if ((e.ctrlKey || e.metaKey) && e.key === 's') {
    e.preventDefault();
    saveDocument();
  }
  // New Tab: Ctrl+T / Cmd+T
  if ((e.ctrlKey || e.metaKey) && e.key === 't') {
    e.preventDefault();
    newTab();
  }
  // Search: Ctrl+F / Cmd+F
  if ((e.ctrlKey || e.metaKey) && e.key === 'f') {
    e.preventDefault();
    openSearch();
  }
});

2. Multi-select ใน List/Grid (Ctrl+Click)

list.addEventListener('click', (e) => {
  const item = e.target.closest('.item');
  if (!item) return;

  if (e.ctrlKey || e.metaKey) {
    // Toggle Selection
    item.classList.toggle('selected');
  } else if (e.shiftKey) {
    // Range Selection (จาก Last Selected)
    selectRange(lastSelected, item);
  } else {
    // Single Selection
    document.querySelectorAll('.item.selected').forEach(el => el.classList.remove('selected'));
    item.classList.add('selected');
    lastSelected = item;
  }
});

3. Mouse Event Modifier Keys (Click, Drag, Wheel)

// Ctrl + Scroll = Zoom
canvas.addEventListener('wheel', (e) => {
  if (e.ctrlKey) {
    e.preventDefault();
    zoom(e.deltaY > 0 ? 0.9 : 1.1, e.clientX, e.clientY);
  }
});

// Ctrl + Drag = Copy/Clone (แทน Move)
element.addEventListener('dragstart', (e) => {
  e.dataTransfer.effectAllowed = e.ctrlKey ? 'copy' : 'move';
});

ข้อควรระวัง

  • Mac vs Windows: Mac ใช้ metaKey (⌘) สำหรับ Shortcut หลัก (Copy, Paste, Save) Windows/Linux ใช้ ctrlKey → ตรวจสอบ (e.ctrlKey || e.metaKey) เสมอ
  • Input Fields: บาง Shortcut (Ctrl+F, Ctrl+P) Browser จัดการเอง ต้อง e.preventDefault() หากจะ Override
  • Focus: Keydown ต้อง Focus ที่ Element หรือ Document ถึงจะจับได้
  • Repeating: Keydown Fire ซ้ำเมื่อกดค้าง ใช้ e.repeat เช็ค

สรุป

event.ctrlKey = Boolean บอกว่า Ctrl ถูกกดค้าง | ใช้ร่วม shiftKey, altKey, metaKey สำหรับ Shortcut, Multi-select, Modifier Click | Mac ใช้ Meta (Cmd) แทน Ctrl สำหรับ Shortcut มาตรฐาน → เช็ค (ctrlKey || metaKey)