Javascript 在div中获取鼠标位置?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14651306/
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
Get mouse position within div?
提问by maxhud
Possible Duplicate:
Mouse position relative to div
getting mouse position with javascript within canvas
How can I get the position of the mouse within a canvas that is a fixed size but has an automatic margin?
如何在固定大小但具有自动边距的画布中获取鼠标的位置?
I can't make its position fixed and can't just use the regular mouse position on the page.
我不能固定它的位置,也不能只使用页面上的常规鼠标位置。
This code works perfectly:
这段代码完美运行:
mouseX = e.pageX - div.offsetLeft;
mouseY = e.pageY - div.offsetTop;
采纳答案by PitaJ
Using jQuery:
使用jQuery:
var divPos = {};
var offset = $("#divid").offset();
$(document).mousemove(function(e){
divPos = {
left: e.pageX - offset.left,
top: e.pageY - offset.top
};
});
回答by dmk
Use event.layerXand event.layerYto get mouse position relative to the current element:
使用event.layerX和event.layerY获取鼠标相对于当前元素的位置:
$('#canvas').mousemove(function(e){
var mousePos = {'x': e.layerX, 'y': e.layerY};
});
回答by Ian Ellis
Taken from jQuery site: Jquery Tutorial site
取自 jQuery 站点:Jquery 教程站点
$(document).mousemove(function(e){
$('#status').html(e.pageX +', '+ e.pageY);
});
NOTE: fixed syntax
注意:固定语法

