Javascript: Get mouse position relative to parent element

走远了吗. 提交于 2019-11-28 10:09:49
Matti Virkkunen

Subtract the position of the parent element (offsetLeft; offsetTop) from the mouse position (pageX; pageY) to get relative position. Remember to take offsetParent into account if you have multiple levels of offsets.

For example:

element.addEventListener("mousedown", function (e) {
  let x = e.pageX - parent.offsetLeft;
  let y = e.pageY - parent.offsetTop;

  console.log(x, y);
});

Where element is your inner element receiving the event, and parent is your desired reference for the coordinates.

jquery offset() method handles parent positioning, so

function onsomemouseevent(e) {
    var x = e.pageX - $(e.target).offset().left;
}

is plain browser abstracted jquery.

Try the offsetParent property. http://help.dottoro.com/ljetdvkl.php

Try this: positionX = document.getElementByID('childId').offsetParent.offsetLeft; positionY = document.getElementByID('childId').offsetParent.offsetLeft;

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!