使用 javascript/jQuery 在父 div 中获取鼠标位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12021751/
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-26 15:05:31  来源:igfitidea点击:

Getting mouse position inside parent div with javascript/jQuery

javascriptjqueryhtml

提问by user1609221

Possible Duplicate:
jQuery get mouse position within an element

可能的重复:
jQuery 获取元素内的鼠标位置

I have a page and inside that page I have a div. If the user clicks inside that div it'll store the X/Y co-ordinates of where they clicked inside that div.

我有一个页面,在该页面内我有一个 div。如果用户在该 div 内单击,它将存储他们在该 div 内单击的位置的 X/Y 坐标。

E.g. if I clicked in the top left corner of the div (no matter where the div was placed on the page) it'd return approximately 0, 0.

例如,如果我单击 div 的左上角(无论 div 放在页面上的哪个位置),它都会返回大约 0, 0。

Is this even possible? and if so, could you tell me how - or even point me in the right direction?

这甚至可能吗?如果是这样,你能告诉我如何 - 甚至指出我正确的方向吗?

回答by JJJ

Use pageXproperty of the event to get the x coordinate relative to the page and pageYto get the y coordinate, then substract the element's coordinates to get the position relative to the element.

使用pageX事件的属性获取相对于页面的x坐标和pageYy坐标,然后减去元素的坐标得到相对于元素的位置。

$( '#target' ).on( 'click', function( e ) {
    var x = e.pageX - this.offsetLeft;
    var y = e.pageY - this.offsetTop;
});?

Demo: http://jsfiddle.net/WhrFt/

演示:http: //jsfiddle.net/WhrFt/

Official tutorial on jquery.com: http://docs.jquery.com/Tutorials:Mouse_Position

jquery.com 上的官方教程:http://docs.jquery.com/Tutorials: Mouse_Position