JavaScript code _javascript tips for getting the mouse position under IE or Firefox

Source: Internet
Author: User
the first piece of code uses global variables to get the location of the real-time mouse.
Copy Code code as follows:

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 for CLIENTX resolution is not the same, ie think clientx is the mouse relative to the top left corner of the page, and Firefox is considered relative to the current position of the upper-left corner of the page. The final result of this code is the position of the upper-left corner of the entire page. The flaw with this code is that xpos and ypos are changed in real time.

the second piece of code is to get the mouse coordinates of the current moment through a function

Copy Code code 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, and this site also provides some simple examples for us to play with. This function is consistent with the function theory just now, triggering the MouseMove event first, and then retrieving the event to determine the browser type separately. The advantage of this code is that it does not apply to global variables, and can be used with the fetch, as long as the function is called to get the mouse coordinates.

These two pieces of code, personal preference for the latter, now first write down this code, this code should be used frequently.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.