在JavaScript中的onMouseMove事件处理程序中,如何获取相对于页面顶部的鼠标位置的x、y坐标?
如果你能使用jQuery,那么这个会有所帮助:
<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;
}
这是经过验证在所有浏览器中都可以使用的方法:
function getMousePos(e) {
return {x:e.clientX,y:e.clientY};
}
现在你可以像这样在事件中使用它:
document.onmousemove=function(e) {
var mousecoords = getMousePos(e);
alert(mousecoords.x);alert(mousecoords.y);
};
注意:上面的函数将返回相对于视口(viewport)的鼠标坐标,不受滚动影响。如果您想获取包括滚动的坐标,则使用下面的函数。
function getMousePos(e) {
return {
x: e.clientX + document.body.scrollLeft,
y: e.clientY + document.body.scrollTop
};
}
使用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')
});
coordinates [0]
,y坐标将是coordinates [1]
。这非常方便,因为您可以通过将'html'
与标记(例如'body'
),类名(例如'.class_name'
)或id(例如'#element_id'
)进行交换,从而获得相对于任何容器的鼠标坐标。onmousemove
的使用有点太慢了。我已经在我的项目中使用了d3.js,但它对于我的用例来说并不够灵活。 - elrobisvar 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))};