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

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

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

ออบเจ็กต์ Map ใน HTML DOM แทนอิลิเมนต์ <map> ใช้ร่วมกับ <img> และ <area> เพื่อสร้าง image map (ภาพที่มีพื้นที่คลิกได้หลายจุด)

ไวยากรณ์ (Syntax)

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

var mapObject = document.createElement("MAP")

คอลเลกชันและคุณสมบัติ (Collections & Properties)

คอลเลกชัน/คุณสมบัติ คำอธิบาย
areasคืนคอลเลกชันของอิลิเมนต์ <area> ทั้งหมดภายใน map
imagesคืนคอลเลกชันของอิลิเมนต์ <img> และ <object> ที่ใช้ map นี้
nameตั้งค่าหรือคืนค่าของแอตทริบิวต์ name สำหรับอิลิเมนต์ <map>

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

ตัวอย่างด้านล่างแสดงการเพิ่ม <area> เข้าไปใน map แบบไดนามิก

<!DOCTYPE html>
<html>
<head>
    <title>Map areas collection</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>
        <fieldset>
            <legend>Map-areas-collection</legend>
            <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/fb/New7Wonders.jpg/276px-New7Wonders.jpg" width="250" height="150" usemap="#7Wonders">
            <map id="WonderWorld" name="7Wonders"></map>
            <div id="divDisplay"></div>
            <input type="button" value="Apply Link" onclick="myWonder()">
        </fieldset>
    </form>
    <script>
        function myWonder() {
            var divDisplay = document.getElementById("divDisplay");
            var newArea = document.createElement("AREA");
            newArea.setAttribute("href", "https://en.wikipedia.org/wiki/Giza_pyramid_complex");
            newArea.setAttribute("shape", "rect");
            newArea.setAttribute("coords", "120,10,10,40");
            document.getElementById("WonderWorld").appendChild(newArea);
            divDisplay.textContent = "Link was applied, hover and click on pyramid of giza.";
        }
    </script>
</body>
</html>

ผลลัพธ์

ก่อนคลิกปุ่ม Apply Link จะแสดงภาพโดยไม่มีลิงก์

หลังคลิกปุ่ม Apply Link จะเพิ่มพื้นที่คลิกได้ (area) บนพีระมิดกีซา คลิกแล้วไปยัง Wikipedia

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

  • Image map ต้องการ: <img usemap="#mapname">, <map name="mapname">, และ <area> หนึ่งหรือหลายอัน
  • แอตทริบิวต์ shape ของ area: rect (สี่เหลี่ยม), circle (วงกลม), poly (หลายเหลี่ยม), default (พื้นที่เหลือ)
  • แอตทริบิวต์ coords รูปแบบต่างกันตาม shape: rect (x1,y1,x2,y2), circle (x,y,radius), poly (x1,y1,x2,y2,...)
  • คอลเลกชัน areas ใช้วนลูปเข้าถึง area ทั้งหมดได้