css 父元素的mousedown事件的offsetX和offsetY错误

rkue9o1l  于 2023-06-07  发布在  其他
关注(0)|答案(2)|浏览(199)

我遇到了一个问题,而得到offsetX上mousedown。下面是我的代码

<!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>

我得到了正确的结果,我想当我的mousedown是在div区域,但它给了我错误的结果,当我的鼠标是在段落区域。我不明白为什么会发生这种情况,因为事件的父元素是DIV元素。
获取结果案例1:当鼠标位于DIV元素顶部时:17px,左:61px
情况1:当我的鼠标在DIV元素顶部:11px,左:9px

7fyelxc5

7fyelxc51#

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

MouseEvent.offsetX
MouseEvent.offsetX只读属性提供该事件和目标节点的填充边缘之间鼠标指针的X坐标偏移量。
因此,在#myP元素内部的<p>元素的情况下,您将获得offsetXoffsetY的不同值。
要始终获得鼠标相对于#myP元素的坐标,可以从MouseEvent.clientXMouseEvent.clientY属性中减去getBoundingClientRect方法给出的lefttop值。
这里有一个例子。

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>
s4n0splo

s4n0splo2#

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

相关问题