鼠标事件:layerX 属性

非标准:此功能是非标准的,并且不在标准轨道上。不要在面向 Web 的生产站点上使用它:它不会对每个用户都有效。实现之间也可能存在很大的不兼容性,并且行为将来可能会发生变化。

MouseEvent.layerX 只读属性返回相对于当前层的事件水平坐标。

此属性考虑了页面的滚动,并返回相对于整个文档的值,除非事件发生在定位元素内部,在这种情况下,返回值相对于定位元素的左上角。

鼠标事件触发时,鼠标指针 x 坐标的像素整数。

示例

html
<html lang="en">
  <head>
    <title>pageX\pageY & layerX\layerY example</title>

    <script>
      function showCoords(evt) {
        const form = document.forms.form_coords;
        const parent_id = evt.target.parentNode.id;
        form.parentId.value = parent_id;
        form.pageXCoords.value = evt.pageX;
        form.pageYCoords.value = evt.pageY;
        form.layerXCoords.value = evt.layerX;
        form.layerYCoords.value = evt.layerY;
      }
    </script>

    <style>
      #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;
      }
    </style>
  </head>

  <body onmousedown="showCoords(event)">
    <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>
  </body>
</html>

规范

此属性不属于任何规范。

浏览器兼容性

BCD 表格仅在启用 JavaScript 的浏览器中加载。