MouseEvent: layerX 屬性

非標準:此特性未標準化。我們不建議在生產環境中使用非標準特性,因為它們瀏覽器支援有限,並且可能會更改或被移除。但是,在沒有標準選項的特定情況下,它們可以是合適的替代方案。

MouseEvent.layerX 只讀屬性返回事件相對於當前圖層的水平座標。

此屬性會考慮頁面的滾動,並返回相對於整個文件的值,除非事件發生在定位元素內部,此時返回的值相對於該定位元素的左上角。

滑鼠事件觸發時,滑鼠指標 x 座標的畫素整數值。

示例

html
<p>To display the mouse coordinates please click anywhere on the page.</p>

<div id="d1">
  <span>
    This is an un-positioned div so clicking it will return layerX/layerY values
    almost the same as pageX/PageY values.
  </span>
</div>

<div id="d2">
  <span>
    This is a positioned div so clicking it will return layerX/layerY values
    that are relative to the top-left corner of this positioned element. Note
    the pageX\pageY properties still return the absolute position in the
    document, including page scrolling.
  </span>

  <span>
    Make the page scroll more! This is a positioned div so clicking it will
    return layerX/layerY values that are relative to the top-left corner of this
    positioned element. Note the pageX\pageY properties still return the
    absolute position in the document, including page scrolling.
  </span>
</div>

<div id="d3">
  <form name="form_coords" id="form1">
    Parent Element id: <input type="text" name="parentId" size="7" /><br />
    pageX: <input type="text" name="pageXCoords" size="7" /> pageY:
    <input type="text" name="pageYCoords" size="7" /><br />
    layerX: <input type="text" name="layerXCoords" size="7" /> layerY:
    <input type="text" name="layerYCoords" size="7" />
  </form>
</div>
css
#d1 {
  border: solid blue 1px;
  padding: 20px;
}

#d2 {
  position: absolute;
  top: 180px;
  left: 80%;
  right: auto;
  width: 40%;
  border: solid blue 1px;
  padding: 20px;
}

#d3 {
  position: absolute;
  top: 240px;
  left: 20%;
  width: 50%;
  border: solid blue 1px;
  padding: 10px;
}
js
function showCoords(evt) {
  const form = document.forms.form_coords;
  const parentId = evt.target.parentNode.id;
  form.parentId.value = parentId;
  form.pageXCoords.value = evt.pageX;
  form.pageYCoords.value = evt.pageY;
  form.layerXCoords.value = evt.layerX;
  form.layerYCoords.value = evt.layerY;
}

window.addEventListener("mousedown", showCoords);

規範

此屬性不屬於任何規範。

瀏覽器相容性