父元素的mousedown事件中offsetX和offsetY值错误。

9
我在获取mousedown的offsetX时遇到了问题。以下是我的代码:
<!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像素
情况2:当我的鼠标悬停在段落元素上时 顶部:11像素,左侧:9像素
2个回答

31
MouseEvent.offsetXMouseEvent.offsetY将给出鼠标指针相对于目标节点填充边缘的坐标。

MouseEvent.offsetX

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

因此,在#myP元素内部的<p>元素的情况下,您会得到不同的offsetXoffsetY值,正如预期的那样。
为了始终获得相对于#myP元素的鼠标坐标,您可以从getBoundingClientRect方法给出的lefttop值中减去MouseEvent.clientXMouseEvent.clientY属性。
以下是一个示例。

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>


@Kushal Jain 这应该被标记为正确答案。对我来说,它完美地运作了。非常聪明的解决方案。 - Syknapse

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

目前您的回答写得不够清晰。请[编辑]以添加更多细节,以便其他人了解这如何回答所提出的问题。您可以在 帮助中心 中找到有关撰写良好回答的更多信息。 - Community

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接