onMouseMove获取鼠标位置
,如果你可以使用jQuery,然后this将帮助:
<div id="divA" style="width:100px;height:100px;clear:both;"></div>
<span></span><span></span>
<script>
$("#divA").mousemove(function(e){
var pageCoords = "(" + e.pageX + ", " + e.pageY + ")";
var clientCoords = "(" + e.clientX + ", " + e.clientY + ")";
$("span:first").text("(e.pageX, e.pageY) - " + pageCoords);
$("span:last").text("(e.clientX, e.clientY) - " + clientCoords);
});
</script>
这里是纯JavaScript唯一的例子:
var tempX = 0;
var tempY = 0;
function getMouseXY(e) {
if (IE) { // grab the x-y pos.s if browser is IE
tempX = event.clientX + document.body.scrollLeft;
tempY = event.clientY + document.body.scrollTop;
}
else { // grab the x-y pos.s if browser is NS
tempX = e.pageX;
tempY = e.pageY;
}
if (tempX < 0){tempX = 0;}
if (tempY < 0){tempY = 0;}
document.Show.MouseX.value = tempX;//MouseX is textbox
document.Show.MouseY.value = tempY;//MouseY is textbox
return true;
}
嗯,JS例子似乎非常类似于http:// www.codelifter.com/main/javascript/capturemouseposition1.html除非没有方便的评论 – RozzA 2015-06-04 21:49:46
'id =“#divA”'和'$(“divA”)' - 有人在写这个时候睡着了 – RozzA 2015-06-05 21:56:26
@RozzA感谢您的关注。 – TheVillageIdiot 2015-06-06 10:19:06
特别是随着鼠标移动事件,火灾快速和激烈,其良好的在使用它们之前减少处理程序 -
var whereAt= (function(){
if(window.pageXOffset!= undefined){
return function(ev){
return [ev.clientX+window.pageXOffset,
ev.clientY+window.pageYOffset];
}
}
else return function(){
var ev= window.event,
d= document.documentElement, b= document.body;
return [ev.clientX+d.scrollLeft+ b.scrollLeft,
ev.clientY+d.scrollTop+ b.scrollTop];
}
})()
document.ondblclick = function(e){alert(whereAt(e))};
使用d3.js仅用于查找鼠标坐标可能有点矫枉过正,但它们有一个非常有用的功能,称为d3.mouse(*container*)
。下面是做你想做的事的例子:
var coordinates = [0,0];
d3.select('html') // Selects the 'html' element
.on('mousemove', function()
{
coordinates = d3.mouse(this); // Gets the mouse coordinates with respect to
// the top of the page (because I selected
// 'html')
});
在上述情况下,x坐标将是coordinates[0]
和y坐标将是coordinates[1]
。这非常方便,因为通过与标签(例如'body'
),类名称(例如'.class_name'
)或id(例如'#element_id'
)交换'html'
,您可以获得与您想要的任何容器相关的鼠标坐标。
+1,但**公平的警告**:这种方法是有点太滞后用于'onmousemove'。我的项目中已经有了d3.js,所以我尝试了一下,但对于我的用例来说,这还不够快。 – elrobis 2015-09-02 19:37:52
这是尝试和作品在所有浏览器:
function getMousePos(e) {
return {x:e.clientX,y:e.clientY};
}
现在你可以在这样一个事件中使用它:
document.onmousemove=function(e) {
var mousecoords = getMousePos(e);
alert(mousecoords.x);alert(mousecoords.y);
};
的
可能重复[如何获得jQuery的鼠标位置没有鼠标 - 事件?](http://stackoverflow.com/questions/4517198/how-to-get-mouse-position-in-jquery-without-mouse-events) – Lucio 2014-10-12 19:56:50