คุณสมบัติ accessKey ของ DOM คืออะไร?
คุณสมบัติ accessKey ของ HTMLElement ใช้สำห อ่าน/ตั้งค่าแอตทริบิวต์ accesskey** ซึ่งกำหนดปุ่มลัด (Shortcut Key) เพื่อให้ Focus หรือ Activate อิลิเมนต์นั้นได้
ไวยากรณ์ (Syntax)
// อ่านค่า var key = element.accessKey; // ตั้งค่า element.accessKey = "g"; // ตัวอักษรเดียว
การกด Shortcut Key ตาม Platform/Browser
| เบราวเซอร์ | Windows/Linux | macOS |
|---|---|---|
| Chrome, Edge, Opera | Alt + Key | Control + Option + Key |
| Firefox | Alt + Shift + Key | Control + Option + Key |
| Safari | Control + Option + Key | Control + Option + Key |
| Internet Explorer (เก่า) | Alt + Key | - |
ตัวอย่างการใช้งาน
<!DOCTYPE html>
<html>
<body>
<a id="googleLink" accesskey="g" href="https://www.google.com/">Google</a>
<p>กด Alt+G (Win/Chrome) เพื่อไป Google</p>
<button onclick="showAccessKey()">แสดง accessKey</button>
<p id="output"></p>
<script>
function showAccessKey() {
var key = document.getElementById("googleLink").accessKey;
document.getElementById("output").innerHTML = "Access Key: " + key;
}
</script>
</body>
</html>
ผลลัพธ์
กดปุ่ม "แสดง accessKey" → แสดง "Access Key: g"
กด Alt+G (Windows Chrome) → ไปที่ Google
แนวทางปฏิบัติที่ดี (Best Practices)
- ใช้ตัวอักษรที่ **ไม่ชนกับ Browser/OS Shortcuts** (หลีกเลี่ยง F, H, E, A, W, R, ฯลฯ)
- ใช้ตัวอักษรแรกของ Label ที่โดดเด่น (Mnemonic) เช่น
accesskey="s"สำหรับ Save - แสดง Access Key ให้ผู้ใช้เห็น (Underline ตัวอักษรใน Label)
- ใช้
<label>ร่วมกับ Form Controls - ทดสอบ Cross-browser/platform
ตัวอย่างแสดง Access Key ด้วย CSS
/* ขีดเส้นใต้ตัวอักษรที่เป็น Access Key */
[accesskey]::after {
content: " [" attr(accesskey) "]";
font-size: 0.8em;
color: #666;
}
/* หรือ underline ตัวอักษรใน Label */
label[for] { position: relative; }
label[for]::before {
content: attr(data-accesskey);
text-decoration: underline;
}
จุดสำคัญ
- Global Attribute: ใช้ได้กับทุกอิลิเมนต์
- ค่าต้องเป็น **ตัวอักษรเดียว** (Single Character)
- Case-insensitive:
accesskey="G"=accesskey="g" - หากซ้ำกัน เบราวเซอร์จะเลือกตัวแรก/สุดท้าย (Implementation Dependent)