javascript 在javascript中获取相对鼠标X/Y
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/4500758/
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
Getting relative mouse X/Y in javascript
提问by Tom Gullen
I have a div somewhere on the page. I then get the mouse XY:
我在页面上的某个地方有一个 div。然后我得到鼠标XY:
        var relativeMouseX = self.gCurrentMouseX - self.gContainerLeft;
        var relativeMouseY = self.gCurrentMouseY - self.gContainerTop;
Where the current mousex/y are obtained via:
当前 mousex/y 是通过以下方式获得的:
// Update mouse coords
this.gUpdateMousePos = function(evt) {
    if (evt === undefined) evt = window.event;
    if (window.event) {
        this.gCurrentMouseX = event.clientX;
        this.gCurrentMouseY = event.clientY;
    }
    else {
        this.gCurrentMouseX = evt.clientX;
        this.gCurrentMouseY = evt.clientY;
    }
}
This worked fine in testing, but when the div is located down a page, it messes up themouse X/Y, as the co-ordinates only seem to be in the viewinwg area and not the entire page.
这在测试中运行良好,但是当 div 位于页面下方时,它会弄乱鼠标 X/Y,因为坐标似乎只在 viewinwg 区域中,而不是整个页面。
X co-ord works fine, because the pages never expand horizontally wider than the browser size, but vertical is a problem!
X 坐标工作正常,因为页面的水平扩展永远不会超过浏览器大小,但垂直是一个问题!
Any ideas how to get mouse X/Y relative to the element?
任何想法如何让鼠标 X/Y 相对于元素?
回答by JCOC611
event.clientX+document.body.scrollLeftand event.clientX+document.body.scrollToporevent.pageXand event.pageY
event.clientX+document.body.scrollLeft和event.clientX+document.body.scrollTop或event.pageX和event.pageY
The first one is just adding current scroll position to the value, the second one is the mouse position relative to the page, not the client window.
第一个只是将当前滚动位置添加到值中,第二个是鼠标相对于页面的位置,而不是客户端窗口。
回答by Kai
You need to account for the parent elements to find a child element's true position on the page. See http://www.quirksmode.org/js/findpos.html
您需要考虑父元素才能找到子元素在页面上的真实位置。见http://www.quirksmode.org/js/findpos.html
 /**
 * Locate the real position of an element,
 * relative to its parent's offsets
 */
function findPos (obj) {
    var curleft = 0,
        curtop = 0;
    if (obj.offsetParent) {
        do {
            curleft += obj.offsetLeft;
            curtop += obj.offsetTop;
        } while (obj = obj.offsetParent);
        return { x: curleft, y: curtop };
    }
}

