Transferred from: http://www.cnblogs.com/dolphinX/archive/2012/10/09/2717119.html
In some DOM operation we often deal with the position of the element, the mouse interactive one often use of aspects, disappointing is that different browsers will have different results or even some browser does not result, this article on the mouse click on the location coordinates to get to do some simple summary, no special declaration code in the IE8, Test compatibility under Firefox,chrome
Mouse click Position coordinates
relative to the screen
If it is related to mouse click to determine the relatively simple location, get to the mouse click event, the event Screenx,screeny gets the click position relative to the screen's left margin and the top margin, regardless of the IFRAME factor, different browser performance is consistent.
function Getmousepos (event) { var e = Event | | window.event; return {' x ': E.screenx, ' y ': ScreenY} }
Relative browser window
Simple code can be implemented, however this is not enough, because in most cases we want to get the mouse click position relative to the coordinates of the browser window, the Clientx,clienty property of the event indicates the mouse click position relative to the left margin of the document, the top margin. So, like, we wrote this code.
function Getmousepos (event) { var e = Event | | window.event; return {' x ': E.clientx, ' y ': ClientY} }
Relative documents
Simple testing is fine, but Clientx and clienty get coordinates relative to the current screen, ignoring page scrolling, which can be useful in many conditions, but what if we need to consider page scrolling, which is relative to the coordinates of the document (BODY element)? With the rolling displacement, let's try to calculate the displacement of the page scrolling.
In fact, the problem in Firefox is much simpler, because Firefox supports the attribute Pagex, and the Pagey attribute, which have already taken the page scrolling into account.
In Chrome, you can calculate page scrolling displacements by document.body.scrollleft,document.body.scrolltop, while in IE you can document.documentElement.scrollLeft , Document.documentElement.scrollTop
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}; }
JavaScript gets mouse click position coordinates