作者:最最后的力气撑起最灿烂的微笑 | 来源:互联网 | 2022-01-26 11:33
代码如下:
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 内核的浏览器使用