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

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

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

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

เราสามารถเปลี่ยนพื้นที่คลิกได้ภายใน map, เปลี่ยนรูปร่าง (shape) ของ image map ตามอินพุตผู้ใช้, หรือจัดการลิงก์ภายใน area element ได้

คุณสมบัติ (Properties)

คุณสมบัติ คำอธิบาย
altตั้งค่าหรือคืนค่าของแอตทริบิวต์ alt
coordsตั้งค่าหรือคืนค่าของแอตทริบิวต์ coords (พิกัด)
hashตั้งค่าหรือคืนค่าส่วน anchor (หลัง #) ของ href
hostตั้งค่าหรือคืนค่า hostname และ port ของ href
hostnameตั้งค่าหรือคืนค่า hostname ของ href
hrefตั้งค่าหรือคืนค่าของแอตทริบิวต์ href ของ area
noHrefตั้งค่าหรือคืนค่า nohref (ล้าสมัยใน HTML5)
originคืนค่า protocol, hostname และ port ของ href
passwordตั้งค่าหรือคืนค่าส่วน password ของ href
pathnameตั้งค่าหรือคืนค่าส่วน pathname ของ href
portตั้งค่าหรือคืนค่าส่วน port ของ href

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

ตัวอย่างด้านล่างแสดงการสร้าง <area> แบบไดนามิกพร้อมลิงก์ไปยัง Maya City

<!DOCTYPE html>
<html>
<body>
    <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/fb/New7Wonders.jpg/276pxNew7Wonders.jpg" width="400" height="400" usemap="#7Wonders">
    <map id="WonderWorld" name="7Wonders"></map>
    <p>Click the button to create an AREA element with a link to "Maya City", which is one of the New Seven Wonders of the World.</p>
    <button onclick="myWonder()">CLICK IT</button>
    <p id="SAMPLE"></p>
    <script>
        function myWonder() {
            var x = document.createElement("AREA");
            x.setAttribute("href", "https://en.wikipedia.org/wiki/Maya_city");
            x.setAttribute("shape", "circle");
            x.setAttribute("coords", "124,58,16");
            document.getElementById("WonderWorld").appendChild(x);
            document.getElementById("SAMPLE").innerHTML = "The AREA element was created, and you can now click on Maya City.";
        }
    </script>
</body>
</html>

ผลลัพธ์

เริ่มต้น: แสดงภาพ 7 Wonders โดยไม่มีพื้นที่คลิกได้

หลังคลิก CLICK IT: สร้าง area รูปวงกลมบน Maya City คลิกแล้วไปหน้า Wikipedia

คำอธิบายโค้ด

  1. สร้าง <img> พร้อม usemap="#7Wonders" เชื่อมกับ map
  2. สร้าง <map id="WonderWorld" name="7Wonders"> ว่างเปล่า
  3. ปุ่ม CLICK IT เรียกฟังก์ชัน myWonder()
  4. ฟังก์ชันสร้าง <area>, ตั้งค่า href, shape, coords, แล้ว append เข้า map

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

  • shape="circle" ต้องการ coords: centerX,centerY,radius
  • shape="rect" ต้องการ coords: x1,y1,x2,y2 (มุมซ้ายบน, มุมขวาล่าง)
  • shape="poly" ต้องการ coords: x1,y1,x2,y2,x3,y3...
  • คุณสมบัติ URL ต่างๆ (href, hostname, pathname, etc.) ทำงานเหมือน <a> element
  • แอตทริบิวต์ alt จำเป็นสำหรับ accessibility (screen readers)