The first piece of code uses global variables to obtain the real-time mouse position.
var xPos;
var yPos;
window.document.onmousemove(function(evt){
evt=evt || window.event;
if(evt.pageX){
xPos=evt.pageX;
yPos= evt.pageY;
} else {
xPos=evt.clientX document.body.scrollLeft-document.body.clientLeft;
yPos=evt.clientY document.body.scrollTop-document.body.clientTop;
}
});
Because IE and Firefox have different parsing of clientX, IE thinks that clientX is the position of the mouse relative to the upper left corner of the entire page, while Firefox thinks it is Position relative to the upper left corner of the currently viewed page. The final result returned by this code is the position of the upper left corner of the entire page. The flaw of this code is that xPos and yPos change in real time.
The second piece of code is to obtain the mouse coordinate value at the current moment through a function
document.onmousemove = mouseMove;
function mouseMove(ev){
ev = ev || window.event;
var mousePos = mouseCoords(ev);
}
function mouseCoords(ev){
if(ev.pageX || ev.pageY){
return {x:ev.pageX, y:ev.pageY} ;
}
return {
x:ev.clientX document.body.scrollLeft - document.body.clientLeft,
y:ev.clientY document.body.scrollTop - document.body.clientTop
};
}
The source of this code is here. This website also provides some simple samples for us to play with. This function is consistent with the function theory just now. It triggers the mousemove event first, and then after obtaining the event, the browser type is determined respectively. The advantage of this code is that it does not apply to global variables and can be used at any time. As long as this function is called, the mouse coordinates can be obtained.
Of these two pieces of code, I personally prefer the latter. Now write down this piece of code. This piece of code should be used frequently.
Statement: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