如果在不同的子元素上移动,MouseEvent.offsetX / Y将重置为0 [英] MouseEvent.offsetX/Y resets to 0 if moving over different child elements

查看:126
本文介绍了如果在不同的子元素上移动,MouseEvent.offsetX / Y将重置为0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

采用以下小提琴

它包含一个具有3个子div的父div。单击侦听器附加到父div,并且应该使用鼠标相对于父div的位置引发警报:

It contains a parent div with 3 child divs. A click-listener is attached to the parent div and should throw alerts with the mouse position relative to the parent div:

const parent = document.getElementById('main');
parent.addEventListener('click', handleMouseClick);

function handleMouseClick(e) {
    alert(e.offsetX, e.offsetY);
}

我希望:单击任何一个子div并获得点击位置相对于父级div(#main)。

What I expect: Click on any of the child divs and get the click position relative to the parent div (#main).

实际发生的情况:OffsetX / Y始终等于相对于我单击的孩子的点击位置。

What actually happens: OffsetX/Y always equals the click position relative to the child I clicked on.

为什么会这样?我该如何解决?有没有其他方法可以将鼠标相对于父div的位置,并考虑潜在的滚动?

Why does this happen? How can I fix it? Is there another way to get the mouse position relative to the parent div, taking potential scrolling into account?

推荐答案

您想要这样:

function handleMouseClick(e) {
  child = e.target.getBoundingClientRect();
    alert(e.offsetX+child.left, e.offsetY+child.top);
}

由于该事件位于顶部,因此为孩子触发了该事件。因此,您可以获取孩子的getBoundingClientRect()并访问其左侧和顶部字段,以确定其相对于父级的位置。希望对您有所帮助!

The event is triggered for the child because it is on top. So you can grab the child's getBoundingClientRect() and you can access it's left and top fields to determine where it is in relation to its parent. I hope that helps!

编辑:如果event.target的父项未位于(0:0),那么您还必须使用父级(可能还有父级的父级,等等)以获取鼠标单击的位置。您可以通过调用parentElement字段(e.target.parentElement)遍历DOM对象的父对象。

If the parent of the event.target is not positioned at (0:0) then you will also have to involve the offset of the parent (and possibly the parent's parent and so on) in order to get the position of the mouse click. You can traverse the parents of DOM objects by calling on the parentElement field (e.target.parentElement).

例如:

function handleMouseClick(e) {
  childBounds = e.target.getBoundingClientRect();
  parentBounds = e.target.parentElement.getBoundingClientRect();
   alert((e.offsetX+childBounds.left-parentBounds.left) + ", "+ (e.offsetY+childBounds.top-parentBounds.top));
}

这篇关于如果在不同的子元素上移动,MouseEvent.offsetX / Y将重置为0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆