JS獲取鼠標坐標的實例方法_javascript技巧
來源:懂視網(wǎng)
責(zé)編:小采
時間:2020-11-27 21:12:05
JS獲取鼠標坐標的實例方法_javascript技巧
JS獲取鼠標坐標的實例方法_javascript技巧: 代碼如下:var restrictX; var restrictY; var tip; // 鼠標坐標 function mousePosition(ev) { return { x : ev.clientX + document.documentElement.scrollLeft - document.documentElement.clie
導(dǎo)讀JS獲取鼠標坐標的實例方法_javascript技巧: 代碼如下:var restrictX; var restrictY; var tip; // 鼠標坐標 function mousePosition(ev) { return { x : ev.clientX + document.documentElement.scrollLeft - document.documentElement.clie
代碼如下:
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 內(nèi)核的瀏覽器使用
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com
JS獲取鼠標坐標的實例方法_javascript技巧
JS獲取鼠標坐標的實例方法_javascript技巧: 代碼如下:var restrictX; var restrictY; var tip; // 鼠標坐標 function mousePosition(ev) { return { x : ev.clientX + document.documentElement.scrollLeft - document.documentElement.clie