Property event.altKey ใน Mouse Event บอกว่า ปุ่ม Alt ถูกกดค้างอยู่หรือไม่ ขณะที่ Mouse Event เกิดขึ้น (click, mousedown, mousemove, etc.)
ตัวอย่างโค้ด
<!DOCTYPE html>
<html>
<body onmousedown="funcAltKey(event)">
<div>Press and hold ALT key and then click here.</div>
<script>
function funcAltKey(event) {
if (event.altKey) {
alert("ALT key: Pressed");
} else {
alert("ALT key: NOT Pressed");
}
}
</script>
</body>
</html>
คำอธิบาย
event.altKey— Boolean:true= กดค้าง,false= ไม่ได้กด- ทำงานกับ Mouse Events ทั้งหมด:
click, dblclick, mousedown, mouseup, mousemove, mouseenter, mouseleave, contextmenu - บน Mac: Option Key = Alt Key
Modifier Keys ใน Mouse Events
| Property | Key | ค่า |
|---|---|---|
altKey | Alt / Option | Boolean |
ctrlKey | Ctrl / Command | Boolean |
shiftKey | Shift | Boolean |
metaKey | Meta / Command / Windows | Boolean |
การใช้งานจริง
- Alternative Actions: Alt+Click = Open in New Tab / Download / Copy Link
- Modifier Combinations:
if (e.ctrlKey && e.shiftKey)— Ctrl+Shift+Click - Game Controls: Alt + Mouse = Camera Rotate
- Accessibility: ตรวจสอบ Modifier สำหรับ Shortcuts
ตัวอย่าง: Custom Context Menu ด้วย Alt+Click
document.addEventListener('contextmenu', (e) => {
if (e.altKey) {
e.preventDefault(); // บล็อก Default Context Menu
showCustomMenu(e.clientX, e.clientY);
}
// ไม่กด Alt = ใช้ Default Browser Menu
});