使用javascript / jQuery获得鼠标在父div中的位置 [英] Getting mouse position inside parent div with javascript/jQuery
问题描述
可能存在重复:
jQuery在元素中获取鼠标位置
我有一个页面,并在该页面内有一个div。
如果用户在该div内部单击,它将存储他们在该div内点击的X / Y坐标。
例如,如果我点击div的左上角(无论div放在页面上的哪个位置),它会返回大约0,0。
这是偶数可能?如果是这样,你能告诉我如何 - 甚至指向正确的方向吗?
pageX
获取相对于页面的x坐标的事件属性, pageY
获取y坐标,然后减去元素的坐标得到 $('#target').on('click',function(e){
var x = e.pageX - this.offsetLeft;
var y = e.pageY - this.offsetTop;
});
演示: http://jsfiddle.net/WhrFt /
jquery.com官方教程: http://docs.jquery.com/Tutorials:Mouse_Position
Possible Duplicate:
jQuery get mouse position within an element
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.
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.
Is this even possible? and if so, could you tell me how - or even point me in the right direction?
Use pageX
property of the event to get the x coordinate relative to the page and pageY
to get the y coordinate, then substract the element's coordinates to get the position relative to the element.
$( '#target' ).on( 'click', function( e ) {
var x = e.pageX - this.offsetLeft;
var y = e.pageY - this.offsetTop;
});
Demo: http://jsfiddle.net/WhrFt/
Official tutorial on jquery.com: http://docs.jquery.com/Tutorials:Mouse_Position
这篇关于使用javascript / jQuery获得鼠标在父div中的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!