javascript onmousemove 获取相对坐标
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4657457/
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
javascript onmousemove get relative coordinates
提问by
function aim() {
var mousex = ?
}
<div class="gameArea" onmousemove="aim();"> </div>
I can't find how to get the mouse coordinates for an onmousemove event in javascript.
我找不到如何在 javascript 中获取 onmousemove 事件的鼠标坐标。
回答by
var guide = null;
function aim(event) {
if(window.event)
event = window.event; //grrr IE
var mousex = event.clientX - guide.offsetLeft;
alert('mouse x' + mousex)
}
function init() {
guide = document.getElementById("guide")
guide.onmousemove = aim;
}
<body onload="init();">
This appears to work on both browsers. I cant do onmousemove="aim();" in html because it doesn't pass the mousemove event object.
这似乎适用于两种浏览器。我不能做 onmousemove="aim();" 在 html 中,因为它不传递 mousemove 事件对象。
回答by sp2danny
The above example using guide.offsetLeftonly works if the enclosing element is at (0,0). If not, you can use guide.getBoundingClientRect().left(and similar for vertical coord)
上面使用guide.offsetLeft 的示例仅在封闭元素位于 (0,0) 时才有效。如果没有,您可以使用guide.getBoundingClientRect().left(垂直坐标类似)
回答by JRomero
Take a lot at the following script. I believe it should be exactly what you're looking for.
在以下脚本中大量使用。我相信它应该正是你正在寻找的。

