The first code uses global variables to obtain the Real-Time mouse position.
Copy codeThe Code is as follows:
Var xPos;
Var yPos;
Specified parameter Doc ument. 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 do not parse clientX differently, IE considers clientX as the position of the cursor relative to the upper left corner of the page, while Firefox regards it as the position relative to the upper left corner of the page currently seen. The final result returned by this code is the position in the upper-left corner of the page. The defect of this Code is that xPos and yPos change in real time.
The second code is to use a function to obtain the mouse coordinate value of the current time.
Copy codeThe Code is as follows:
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 examples for us to play. This function is consistent with the previous function theory. The mousemove event is triggered first, and then the browser type is determined after the event is obtained. The advantage of this Code is that it does not apply to global variables and can be used as needed. You only need to call this function to obtain the mouse coordinates.
These two pieces of code, which is preferred to the latter, are written down first. This piece of code should be frequently used.