Javascript code for obtaining the mouse position in IE or Firefox

Source: Internet
Author: User

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.

Related Article

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.