Home > Web Front-end > JS Tutorial > JS instance method to obtain mouse coordinates_javascript skills

JS instance method to obtain mouse coordinates_javascript skills

WBOY
Release: 2016-05-16 17:28:30
Original
1251 people have browsed it
Copy code The code is as follows:

var restrictX;
var restrictY;
var tip;
// Mouse coordinates
function mousePosition(ev) {
return {
x : ev.clientX document.documentElement.scrollLeft - document.documentElement.clientLeft,
y : ev.clientY document .documentElement.scrollTop - document.documentElement.clientTop
};
}
// Mouse event
function mouseMove(ev) {
ev = ev || window.event;
var mousePos = mousePosition(ev);
restrictX = mousePos.x;
restrictY = mousePos.y;
}
document.onmousemove = mouseMove;
document.onclick = mouseMove;

The values ​​obtained by the above code in Google and Sohu browsers will be inaccurate and need to be modified, as follows:
Copy code The code is as follows:

var restrictX;
var restrictY;
var tip;
// Mouse coordinates
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
};
}
// Mouse event
function mouseMove(ev){
ev = ev || window.event;
var mousePos = mousePosition(ev);
restrictX = mousePos.x;
restrictY = mousePos.y;
}
document.onmousemove = mouseMove;
document.onclick = mouseMove;

Copy code The code is as follows:

var scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft;
var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;

This The two sentences are, if you can get the mouse coordinates, go to the front, otherwise use the later method to get the mouse coordinates. The ones after "||" are for browsers with WebKit kernel.
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template