ออบเจ็กต์ MenuItem (MenuItem Object)
ออบเจ็กต์ MenuItem ใน HTML DOM แทนอิลิเมนต์ <menuitem> ใช้สำหรับสร้างรายการในเมนูบริบท (context menu) หรือเมนูคำสั่ง
หมายเหตุ: อิลิเมนต์ <menuitem> รองรับเฉพาะใน Mozilla Firefox เท่านั้น ไม่รองรับใน Chrome, Edge, Safari
ไวยากรณ์ (Syntax)
การสร้างอิลิเมนต์ <menuitem>
var menuItemObject = document.createElement("MENUITEM")
คุณสมบัติ (Properties)
| คุณสมบัติ | คำอธิบาย |
|---|---|
checked | ตั้งค่าหรือคืนค่า (true/false) ว่าเมนูไอเท็มควรถูกติ๊กหรือไม่ |
command | ตั้งค่าหรือคืนค่าของแอตทริบิวต์ command |
default | ตั้งค่าหรือคืนค่าว่า menuItem ควรเป็นค่าเริ่มต้นหรือไม่ |
disabled | ตั้งค่าหรือคืนค่าว่าเมนูไอเท็มควรถูกปิดใช้งานหรือไม่ |
icon | ตั้งค่าหรือคืนค่ารูปภาพที่แทน menuItem |
label | ตั้งค่าหรือคืนค่าของแอตทริบิวต์ label ของ menuItem |
radiogroup | ตั้งค่าหรือคืนค่าของแอตทริบิวต์ radiogroup ของ menuItem |
type | ตั้งค่าหรือคืนค่าของแอตทริบิวต์ type ของ menuItem |
ตัวอย่างการใช้งาน
ตัวอย่างด้านล่างแสดงการใช้ <menu> และ <menuitem> สร้าง context menu
<!DOCTYPE html>
<html>
<head>
<title>Menu Object</title>
<style>
form { width: 70%; margin: 0 auto; text-align: center; }
* { padding: 2px; margin: 5px; }
input[type="button"] { border-radius: 10px; }
</style>
</head>
<body>
<form contextmenu="MENU">
<fieldset>
<legend>Menu-Object</legend>
<label for="urlSelect">URL ปัจจุบัน:</label>
<input type="url" size="30" id="urlSelect" value="https://www.example.com/aboutUs">
<div id="divDisplay"></div>
</fieldset>
<menu type="context" id="MENU">
<menuitem label="Get URL" onclick="contextFunction(1);"></menuitem>
<menuitem label="Get Hostname" onclick="contextFunction(2);"></menuitem>
</menu>
</form>
<script>
var divDisplay = document.getElementById("divDisplay");
var urlSelect = document.getElementById("urlSelect");
function gethref() {
divDisplay.textContent = 'URL Path: ' + location.href;
}
function getHostname() {
divDisplay.textContent = 'Hostname: ' + location.hostname;
}
function contextFunction(role) {
if (role === 1) this.gethref();
else this.getHostname();
}
</script>
</body>
</html>
ผลลัพธ์
คลิกขวาที่ฟอร์ม จะแสดง context menu ที่มี 2 รายการ: Get URL และ Get Hostname
คลิก Get URL จะแสดง URL ทั้งหมด
คลิก Get Hostname จะแสดง hostname
คำอธิบายเพิ่มเติม
- <menuitem> เป็นส่วนหนึ่งของ HTML 5.1 แต่ถูกนำออกจากมาตรฐาน HTML Living Standard
- Firefox เป็นเบราว์เซอร์เดียวที่รองรับอย่างเต็มที่
- สำหรับ cross-browser compatibility ควรใช้ JavaScript custom context menu แทน
- แอตทริบิวต์
typeสามารถเป็นcommand,checkbox,radio