In some DOM operations we often deal with the location of elements, mouse interactive a frequently used aspect, it is disappointing that different browsers will have different results or even some browsers have no results, this article on the mouse click position coordinates to get some simple summary, no special statement code in IE8, Test compatibility under Firefox,chrome
Mouse click Position coordinates
Relative to screen
If it is related to the mouse click to determine the location is relatively simple, get to the mouse click event, the event Screenx,screeny get the click Position relative to the screen left margin and the top margin, regardless of the iframe factors, different browsers performance is also consistent.
Copy Code code as follows:
function Getmousepos (event) {
var e = Event | | window.event;
return {' x ': E.screenx, ' y ': ScreenY}
}
relative browser window
Simple code can be implemented, but this is not enough, because in most cases we want to get the mouse click position relative to the browser window coordinates, the event's Clientx,clienty property indicates the mouse click position relative to the document's left margin, the top margin. So, like, we wrote this code.
Copy Code code as follows:
function Getmousepos (event) {
var e = Event | | window.event;
return {' x ': E.clientx, ' y ': ClientY}
}
Relative Document
Simple tests are fine, but Clientx and clienty get the coordinates relative to the current screen, ignoring the page scrolling factor, which is useful in many conditions, but what if we need to consider page scrolling, which is relative to the coordinates of the document (the BODY element)? Plus the rotation of the displacement on it, below we try how to calculate the page scrolling displacement.
In fact, under the Firefox problem will be much simpler, because Firefox support attribute Pagex, and Pagey properties, these two properties have been the page scrolling calculation.
In Chrome, you can calculate the page scrolling displacement by document.body.scrollleft,document.body.scrolltop, while in IE you can pass the Document.documentElement.scrollLeft , Document.documentElement.scrollTop
Copy code code as follows:
function Getmousepos (event) {
var e = Event | | window.event;
var scrollx = Document.documentElement.scrollLeft | | Document.body.scrollLeft;
var scrolly = Document.documentElement.scrollTop | | Document.body.scrollTop;
var x = E.pagex | | E.clientx + scrollx;
var y = E.pagey | | E.clienty + scrolly;
Alert (' x: ' + x + ' \ny: ' + y);
return {' X ': x, ' y ': y};
}