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

ใช้ JavaScript สร้าง Client-side Image Map

Client-side Image Map ใช้ Attribute usemap ใน <img> ร่วมกับ <map> และ <area> Tags กำหนดพื้นที่คลิกได้บนรูปภาพ

โครงสร้าง

<img src="image.jpg" usemap="#mapName" />
<map name="mapName">
  <area shape="rect|circle|poly" coords="..." href="..." alt="..." />
</map>

Shape และ Coords

ShapeCoords Formatตัวอย่าง
rectx1,y1,x2,y2ซ้ายบน, ขวาล่าง
circlex,y,radiusศูนย์กลาง, รัศมี
polyx1,y1,x2,y2,x3,y3...จุดมุมของ Polygon
default-พื้นที่อื่นๆ

ตัวอย่างสมบูรณ์

<html>
  <head>
    <title>Using JavaScript Image Map</title>
    <script>
      function showTutorial(name) {
        document.myform.stage.value = name;
      }
    </script>
  </head>
  <body>
    <form name="myform">
      <input type="text" name="stage" size="20" />
    </form>

    <img src="/images/usemap.gif" alt="HTML Map" border="0" usemap="#tutorials" />

    <map name="tutorials">
      <area shape="poly"
        coords="74,0,113,29,98,72,52,72,38,27"
        href="/perl/index.htm" alt="Perl Tutorial"
        target="_self"
        onMouseOver="showTutorial('perl')"
        onMouseOut="showTutorial('')" />

      <area shape="rect"
        coords="22,83,126,125"
        href="/html/index.htm" alt="HTML Tutorial"
        target="_self"
        onMouseOver="showTutorial('html')"
        onMouseOut="showTutorial('')" />

      <area shape="circle"
        coords="73,168,32"
        href="/php/index.htm" alt="PHP Tutorial"
        target="_self"
        onMouseOver="showTutorial('php')"
        onMouseOut="showTutorial('')" />
    </map>
  </body>
</html>

Accessibility (เข้าถึงได้)

  • ใส่ alt ในทุก <area>
  • ใช้ tabindex ให้ Focus ได้ด้วย Keyboard
  • ให้ href ชี้ไป URL จริง (Fallback เมื่อ JS ปิด)

JavaScript Enhancement

// เพิ่ม Event Listeners แทน Inline Handlers
document.querySelectorAll('area').forEach(area => {
  area.addEventListener('mouseenter', () => showTutorial(area.dataset.tutorial));
  area.addEventListener('mouseleave', () => showTutorial(''));
});

หมายเหตุ: Image Maps ใช้งานได้ใน HTML ทุกยุค แต่ Responsive Design ยาก (Coords คงที่) → ใช้ SVG หรือ CSS Mapping แทนในปัจจุบัน