父元素的鼠标关闭事件时错误的偏移量 X 和偏移量 Y

Wrong offsetX and offsetY on mousedown event of parent element

本文关键字:偏移量 错误 事件 元素 鼠标      更新时间:2023-09-26

我在鼠标按下时遇到偏移量时遇到问题。这是我下面的代码

<!DOCTYPE html>
<html>
    <body>
        <div id="myP" onmousedown="mouseDown()">
            Click the text! The mouseDown() function is triggered when the mouse button is pressed down over this paragraph,
            <p style="margin-left:50px">
             and sets the color of the text to red. The mouseUp() function is triggered when the mouse button is released, 
            </p>
            and sets the color of the text to green.
        </div>
        <script>
            function mouseDown() {
                var left = event.offsetX;
                var top = event.offsetY;
                console.log(top+"::"+left);
            }
        </script>
    </body>
</html>
当我的鼠标按下在div 区域上时,我

得到了我想要的正确结果,但是当我的鼠标悬停在段落区域上时,它会给我错误的结果。我不明白为什么会发生这种情况,因为事件是父元素,即 DIV 元素。

获取结果情况 1:当我的鼠标悬停在 DIV 元素上时 上图:17 像素,左侧:61 像素

情况 1:当我的鼠标悬停在 DIV 元素上时 上图:11 像素,左上:9 像素

MouseEvent.offsetXMouseEvent.offsetY 将为您提供鼠标指针相对于目标节点填充边缘的坐标。

MouseEvent.offsetX

MouseEvent.offsetX 只读属性提供该事件与目标节点的填充边缘之间的鼠标指针 X 坐标中的偏移量。

因此,对于#myP元素内的<p>元素,您可以按预期获得不同的offsetXoffsetY值。

要始终获取相对于 #myP 元素的鼠标坐标,您可以做的是从MouseEvent.clientXMouseEvent.clientY属性中减去该方法给出lefttopgetBoundingClientRect

下面是一个示例。

var myP = document.getElementById('myP'),
    output = document.getElementById('output');
function mouseDown(e) {
  var rect = e.currentTarget.getBoundingClientRect(),
      offsetX = e.clientX - rect.left,
      offsetY = e.clientY - rect.top;
  output.textContent = "Mouse-X: " + offsetX + ", Mouse-Y: " +  offsetY;
  console.log("Mouse-X: " + offsetX, "Mouse-Y: " + offsetY);
}
myP.addEventListener('mousedown', mouseDown, false);
body {
  margin: 0;
  font-family: sans-serif;
}
#myP {
  background: lawngreen;
  margin-left: 50px;
}
#myP > p {
  background: yellow;
  margin-left: 50px;
}
#myP > div > p {
  background: red;
  color: white;
  margin-left: 100px;
}
<div id="myP">
  Click the text! The mouseDown() function is triggered when the mouse button is pressed down over this paragraph,
  <p>
    andsets the color of the text to red. The mouseUp() function is triggered when the mouse button is released,
  </p>
  <div>
    <p>
      Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aut quaerat dolor modi et quidem repudiandae vero, recusandae laborum quae veritatis, doloribus similique accusamus quibusdam voluptate, dolore fugiat eum. Corporis, porro.
    </p>
  </div>
  and sets the color of the text to green.
</div>
<p id="output"></p>

作为快速解决方案,您可以将pointer-events: none;应用于根子节点