[英]Why am I getting wrong offsetX and offsetY in my event handler?
[英]Wrong offsetX and offsetY on mousedown event of parent element
我在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>
当我的mousedown在div区域时,我得到了正确的结果,但是当我的鼠标在段落区域上时,它给出了错误的结果。 我无法理解为什么会发生这种情况,因为event是父元素,它是DIV元素。
获得结果案例1:当我的鼠标在DIV元素顶部时:17px,左:61px
案例1:当我的鼠标在DIV元素顶部时:11px,左:9px
MouseEvent.offsetX或MouseEvent.offsetY将为您提供相对于目标节点填充边缘的鼠标指针的坐标。
MouseEvent.offsetX只读属性提供该事件与目标节点的填充边缘之间的鼠标指针的X坐标中的偏移量。
因此,对于#myP
元素中的<p>
元素,您可以按预期获得offsetX
和offsetY
不同值。
总是得到相对于#myP
元素的鼠标坐标,你可以做的是从MouseEvent.clientX
和MouseEvent.clientY
属性中减去getBoundingClientRect
方法给出的left
和top
值。
这是一个例子。
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.