Property event.pageX ใน Mouse Event คืนค่า Horizontal Coordinate (X) ของ Mouse Pointer เทียบกับ Document 全体 (รวม Scroll)
ตัวอย่างโค้ด
<!DOCTYPE html>
<html>
<body>
<p onclick="coordsFunc(event)">Click here to get the x (horizontal) and y (vertical) coordinates of the mouse pointer.</p>
<script>
function coordsFunc(event) {
var x_coord = event.pageX;
var y_coord = event.pageY;
var xycoords = "X coords= " + x_coord + ", Y coords= " + y_coord;
document.write(xycoords);
}
</script>
</body>
</html>
คำอธิบาย
event.pageX— X Coordinate Relative to Document (Scroll แล้วค่าเปลี่ยน)event.pageY— Y Coordinate Relative to Document- คู่กันเสมอ: ใช้
pageXและpageYร่วมกันเพื่อได้ Document Coordinates
Mouse Coordinate Systems เปรียบเทียบ
| Property | Relative To | Scroll Affects | ใช้เมื่อ |
|---|---|---|---|
pageX/Y | Document | ✅ ใช่ | Element Position, Document Coordinates |
clientX/Y | Viewport (Window) | ❌ ไม่ | UI Position, Tooltip, Modal Placement |
screenX/Y | Physical Screen | ❌ ไม่ | Multi-monitor, Window Positioning |
offsetX/Y | Target Element (Padding Edge) | ❌ ไม่ | Canvas Drawing, Relative Position |
layerX/Y | Current Layer | ❌ ไม่ | Legacy |
การใช้งานจริง
- Tooltip/Context Menu Position:
pageX, pageY(Scroll แล้วอยู่ตำแหน่งเดิมใน Document) - Drag & Drop: คำนวณ Offset ใน Document Coordinates
- Analytics: Click Heatmap (Document Coordinates)
- Canvas:
offsetX/YหรือclientX - canvas.getBoundingClientRect().left
Polyfill สำหรับ Browser เก่า (IE8-)
if (!('pageX' in event)) {
event.pageX = event.clientX + document.documentElement.scrollLeft;
event.pageY = event.clientY + document.documentElement.scrollTop;
}