如何获得相对于父div的鼠标坐标?使用Javascript

Gri*_*Lab 19 javascript events mousemove

我目前有一个div与其中的其他元素结构.

类似于下面的东西;

<div id="container" style="position: relative; width: 500px; height: 500px;">
     <div style="position: absolute; left: 50px; top: 50px;"></div>
     <div style="position: absolute; left: 100px; top: 100px;"></div>
</div>
Run Code Online (Sandbox Code Playgroud)

我试图获取相对于div的div的鼠标位置container.

到目前为止,我有这个;

function onMousemove(event) {

    x = event.offsetX;
    y = event.offsetY;
};

var elem = document.getElementById("container");
elem.addEventListener("mousemove", onMousemove, false);
Run Code Online (Sandbox Code Playgroud)

如果带有id的div container没有子节点,这可以正常工作.当containerdiv有子节点时,它会获得相对于孩子而不是父节点的鼠标坐标.

我的意思是,如果鼠标位于x: 51, y: 51相对于父div 的位置,它实际上将x: 1, y: 1使用上面给出的html相对于子div 返回.

我怎样才能实现我想要的,请不要图书馆.

编辑

tymeJV善意地说明了上面发生的事情.

http://jsfiddle.net/N6PJu/1

Nik*_*kov 52

接受的答案在Chrome中对我不起作用.这是我解决它的方式:

function relativeCoords ( event ) {
  var bounds = event.target.getBoundingClientRect();
  var x = event.clientX - bounds.left;
  var y = event.clientY - bounds.top;
  return {x: x, y: y};
}
Run Code Online (Sandbox Code Playgroud)

  • 很优雅的解决方案 要回答OP的问题,你只需要将`event.target`换成`document.getElementById("container")`. (2认同)
  • 应该注意的是,“getBoundingClientRect”的成本很高,因为它会导致[布局抖动](https://gist.github.com/paulirish/5d52fb081b3570c81e3a)。 (2认同)

Ale*_*sky 7

尽管 Nikita Volkov 的答案相当可靠,但在某些情况下可能无法按预期工作。

我建议使用currentTarget而不是target

const handleEvent = (event) => 
{
  const bounds = event.currentTarget.getBoundingClientRect();
  const x = event.clientX - bounds.left;
  const y = event.clientY - bounds.top;
  // Now x and y are the relative coordinates.
}
Run Code Online (Sandbox Code Playgroud)

注意:

  • event.target是触发事件的元素(例如,用户单击或悬停在其上)。
  • event.currentTarget是事件侦听器附加到的元素。

当您想要将侦听器附加到某个具有多个子元素的元素时,它会产生不同的效果。

例如,

<div onMouseMove={handleEvent} id="div0">
  <div style={{'height': 200, 'width': 200}} id="div1">
  </div>
  <div style={{'height': 200, 'width': 200}} id="div2">
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

如果您将event.target鼠标悬停在其上,您将获得您可能希望它们相关的div2相对坐标。然后就可以了。div2div0event.currentTarget


Git*_*LAB 6

本质上:'mouseposition'-'父元素位置'='相对于父元素的鼠标位置'

所以我在这里修改了您的功能:

function onMousemove(e){
    var m_posx = 0, m_posy = 0, e_posx = 0, e_posy = 0,
           obj = this;
    //get mouse position on document crossbrowser
    if (!e){e = window.event;}
    if (e.pageX || e.pageY){
        m_posx = e.pageX;
        m_posy = e.pageY;
    } else if (e.clientX || e.clientY){
        m_posx = e.clientX + document.body.scrollLeft
                 + document.documentElement.scrollLeft;
        m_posy = e.clientY + document.body.scrollTop
                 + document.documentElement.scrollTop;
    }
    //get parent element position in document
    if (obj.offsetParent){
        do { 
            e_posx += obj.offsetLeft;
            e_posy += obj.offsetTop;
        } while (obj = obj.offsetParent);
    }
    // mouse position minus elm position is mouseposition relative to element:
    dbg.innerHTML = ' X Position: ' + (m_posx-e_posx) 
                  + ' Y Position: ' + (m_posy-e_posy);
}

var elem = document.getElementById('container');
elem.addEventListener('mousemove', onMousemove, false);

var dbg=document.getElementById('dbg');  //debut output div instead of console
Run Code Online (Sandbox Code Playgroud)

这是一个正在工作的演示小提琴。正如您在代码中所看到的,这也将查看文档的滚动位置。

PPK关于“ 事件属性 ”和“ 查找位置 ” 的文章一如既往地不错!

希望这可以帮助!

更新:
我其实在PPK的代码中发现的错误(多么难得的是?!):我纠正错误var的:
if (!e) var e = window.event;if (!e){e = window.event;}