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

ออบเจ็กต์ Menu ใน HTML DOM

ออบเจ็กต์ Menu (Menu Object)

ออบเจ็กต์ Menu ใน HTML DOM แทนอิลิเมนต์ <menu> ใช้เป็นคอนเทนเนอร์สำหรับกลุ่มของคำสั่ง (commands) หรือ <menuitem>

หมายเหตุ: อิลิเมนต์ <menu> รองรับเฉพาะใน Mozilla Firefox เท่านั้น ไม่รองรับใน Chrome, Edge, Safari

ไวยากรณ์ (Syntax)

การสร้างอิลิเมนต์ <menu>

var menuObject = document.createElement("MENU")

ตัวอย่างการใช้งาน

ตัวอย่างด้านล่างแสดงการใช้ <menu> สร้าง context menu พร้อม menuitem

<!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 จะแสดง URL ทั้งหมด

คลิก Get Hostname จะแสดง hostname

คำอธิบายเพิ่มเติม

  • <menu> เดิมทีใช้สำหรับ toolbar หรือ context menu
  • แอตทริบิวต์ type กำหนดประเภทเมนู: context (context menu), toolbar (toolbar), list (รายการคำสั่ง)
  • ในปัจจุบัน <menu> และ <menuitem> ถูก deprecated แล้ว
  • ทางเลือกที่ดีกว่า: ใช้ <div role="menu"> พร้อม ARIA attributes และ JavaScript