javascript 如何获得准确的鼠标按下坐标?为什么我的代码不起作用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7608814/
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
How to get the exact mouse down coordinate? Why my code does not work?
提问by Leem.fin
I would like to show something at the mouse down place, I tried to use :
我想在鼠标按下的地方显示一些东西,我尝试使用:
$('#my-graph').mousedown(function(evt){
// show object at:
var x= evt.screenX, y=evt.screenY;
//or show object at:
var x2=evt.pageX, y2=evt.pageY;
//code to render object at (x,y) and (x2,y2)
......
});
But neither of the above (x, y) and (x2,y2) place the rendered object at the mouse clicked place, and show the object some distance away from mouse down place, why?
但是上面的 (x, y) 和 (x2,y2) 都没有将渲染对象放置在鼠标点击的地方,并且显示对象离鼠标按下的地方有一段距离,为什么?
I render the object with a position attributes, the position is relative to the #my-graphdiv, left up most corner of the div is supposed to be the origin point(0,0)
我用位置属性渲染对象,位置是相对于#my-graphdiv,div 的最左上角应该是原点(0,0)
回答by pimvdb
You seem to want offsetX
and offsetY
: http://jsfiddle.net/f52Gg/.
你似乎想要offsetX
和offsetY
:http: //jsfiddle.net/f52Gg/。
$("div").mousedown(function(e){
alert(e.offsetX + " " + e.offsetY);
});