父元素的鼠标关闭事件时错误的偏移量 X 和偏移量 Y
Wrong offsetX and offsetY on mousedown event of parent element
我在鼠标按下时遇到偏移量时遇到问题。这是我下面的代码
<!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.offsetX 或 MouseEvent.offsetY 将为您提供鼠标指针相对于目标节点填充边缘的坐标。
MouseEvent.offsetX
MouseEvent.offsetX 只读属性提供该事件与目标节点的填充边缘之间的鼠标指针 X 坐标中的偏移量。
因此,对于#myP
元素内的<p>
元素,您可以按预期获得不同的offsetX
和offsetY
值。
要始终获取相对于 #myP
元素的鼠标坐标,您可以做的是从MouseEvent.clientX
和MouseEvent.clientY
属性中减去该方法给出left
和top
值getBoundingClientRect
。
下面是一个示例。
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;
应用于根子节点
相关文章:
- 使用javascript ajax post方法的未定义偏移PHP错误
- 添加新数据时D3.JS条形图列偏移量
- 当偏移量改变时滚动顶部
- 引导数据偏移量底部
- 可以在调整窗口大小时重新调整stellar.js的元素偏移量
- 可滚动元素,如何在调整大小时更改顶部偏移量
- 使用JavaScript日期的任何时间的时区偏移量
- 时刻时区:UTC 偏移量差异
- jQuery偏移量顶部没有'工作不正常
- 如何获取当前时区偏移量(并正确格式化)
- 类型错误: $(..).偏移量(..)未定义,偏移量存在
- 父元素的鼠标关闭事件时错误的偏移量 X 和偏移量 Y
- 滚动侧边栏抛出 Javascript 错误“无法调用 null 的方法'偏移量'
- 如何添加新的输入行并插入数据库并出现错误 未初始化的字符串偏移量:0 in
- Javascript 选择返回错误的偏移量
- Jquery偏移量属性不可读错误
- jQuery在动态加载内容后滚动到错误的偏移量
- javascript的getTimezoneOffset返回错误的偏移量
- Jquery UI位置:顶部偏移量错误
- preg_match错误,货币转换器,未定义偏移量:1