JS instance method for obtaining mouse coordinates

Source: Internet
Author: User

Copy codeThe Code is as follows:
Var restrictX;
Var restrictY;
Var tip;
// Mouse coordinates
Function mousePosition (ev ){
Return {
X: ev. clientX + document.doc umentElement. scrollLeft-document.doc umentElement. clientLeft,
Y: ev. clientY + document.doc umentElement. scrollTop-document.doc umentElement. 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 from the above Code in Google and Sohu browsers are inaccurate and need to be modified as follows:
Copy codeThe Code is as follows:
Var restrictX;
Var restrictY;
Var tip;
// Mouse coordinates
Function mousePosition (ev ){
Var scrollLeft = document.doc umentElement. scrollLeft | document. body. scrollLeft;
Var scrollTop = document.doc umentElement. scrollTop | document. body. scrollTop;
Return {
X: ev. clientX + scrollLeft-document.doc umentElement. clientLeft,
Y: ev. clientY + scrollTop-document.doc umentElement. 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 codeThe Code is as follows:
Var scrollLeft = document.doc umentElement. scrollLeft | document. body. scrollLeft;
Var scrollTop = document.doc umentElement. scrollTop | document. body. scrollTop;

If the mouse coordinates can be obtained, go to the front. Otherwise, use the following method to obtain the mouse coordinates. "|" is followed by the WebKit kernel browser.

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.