這篇文章介紹了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 內核的浏覽器使用