这篇文章介绍了JS获取鼠标坐标的实例方法
有需要的朋友可以参考一下
复制代码 代码如下:
var restrictX;
var restrictY;
var tip;
// 鼠标坐标
function mousePosition(ev) {
return {
x : ev
clientX + document
documentElement
scrollLeft
document
documentElement
clientLeft
y : ev
clientY + document
documentElement
scrollTop
document
documentElement
clientTop
};
}
// 鼠标事件
function mouseMove(ev) {
ev = ev || window
event;
var mousePos = mousePosition(ev);
restrictX = mousePos
x;
restrictY = mousePos
y;
}
document
onmousemove = mouseMove;
document
onclick = mouseMove;
上面的代码在谷歌和搜狐浏览器中获取的值会不准确需进行修改如下
复制代码 代码如下:
var restrictX;
var restrictY;
var tip;
// 鼠标坐标
function mousePosition(ev){
var scrollLeft = document
documentElement
scrollLeft || document
body
scrollLeft;
var scrollTop = document
documentElement
scrollTop || document
body
scrollTop;
return {
x:ev
clientX + scrollLeft
document
documentElement
clientLeft
y:ev
clientY + scrollTop
document
documentElement
clientTop
};
}
// 鼠标事件
function mouseMove(ev){
ev = ev || window
event;
var mousePos = mousePosition(ev);
restrictX = mousePos
x;
restrictY = mousePos
y;
}
document
onmousemove = mouseMove;
document
onclick = mouseMove;
复制代码 代码如下:
var scrollLeft = document
documentElement
scrollLeft || document
body
scrollLeft;
var scrollTop = document
documentElement
scrollTop || document
body
scrollTop;
这两句为如果能获取到鼠标坐标则去前面否则用后面的方法获取鼠标坐标“|| ”后面的是给WebKit 内核的浏览器使用