如何获取相对于父 div 的鼠标坐标?Javascript

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16154857/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 03:29:10  来源:igfitidea点击:

How can I get the mouse coordinates relative to a parent div? Javascript

javascripteventsmousemove

提问by GriffLab

I currently have a div structured with other elements inside of it.

我目前有一个由其他元素构成的 div。

Something similar to below;

类似于下面的东西;

<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>

I am trying to get the mouse position relative to the div with the id container.

我正在尝试使用 id 获取相对于 div 的鼠标位置container

So far I have this;

到目前为止,我有这个;

function onMousemove(event) {

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

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

This works fine if the div with the id containerhas no children. When the containerdiv has children it gets the mouse co-ordinates relative to the child rather than the parent.

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

What I mean by this is if the mouse was at a position of x: 51, y: 51relative to the parent div, it would actually return x: 1, y: 1relative to the child div, using the html given above.

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

How can I achieve what I want, no libraries please.

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

EDIT

编辑

tymeJV has kindly made a jsfiddle of what is happening above.

tymeJV 对上面发生的事情做了一个 jsfiddle。

http://jsfiddle.net/N6PJu/1

http://jsfiddle.net/N6PJu/1

采纳答案by GitaarLAB

In essence: 'mouseposition' - 'parent element position' = 'mouseposition relative to parent element'

本质上:'mouseposition' - 'parent element position' = 'mouseposition relative to parent element'

So here I modified your function:

所以在这里我修改了你的函数:

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

Here is a working demo fiddle. As you can read in the code, this also looks at the document's scroll position.

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

PPK's article on 'event properties' and 'find position' are (as always) a good read!

PPK 关于“事件属性”和“查找位置”的文章(一如既往)值得一读!

Hope this helps!

希望这可以帮助!

Update:
I actually found an error in ppk's code (how rare is that?!): I corrected the erroneous varin:
if (!e) var e = window.event;to if (!e){e = window.event;}

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

回答by Nikita Volkov

The accepted answer didn't work for me in Chrome. Here's how I solved it:

接受的答案在 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};
}

回答by Willem Mulder

Get the screenX and screenY properties to see where the mouse is on the screen (and possibly take the scrollHeight into account!).

获取 screenX 和 screenY 属性以查看鼠标在屏幕上的位置(并可能将 scrollHeight 考虑在内!)。

Then get the left and top of the container element and calculate the offset between them: that is the position of the mouse in the element.

然后获取容器元素的left和top并计算它们之间的偏移量:即鼠标在元素中的位置。

See https://developer.mozilla.org/en-US/docs/DOM/MouseEventfor more details.

有关更多详细信息,请参阅https://developer.mozilla.org/en-US/docs/DOM/MouseEvent

回答by Le Fem

Html

html

<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>

Javascript

Javascript

function onMousemove(event) {
    x = event.layerX; // position x relative to div
    y = event.layerY; // position y relative to div 
};

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