This article mainly introduces various methods for obtaining the mouse position based on JavaScript. For more information, see DOM operations, mouse interaction is a frequently used aspect. It is disappointing that different browsers have different results or even some browsers have no results, this article makes some simple summary by clicking the coordinates of the cursor and position. There is no special declaration code for testing compatibility in IE8, FireFox, and Chrome.
Mouse Click coordinates
Relative to the screen
If it is relatively simple to determine the position of a mouse click, after obtaining the mouse click event, the event screenX and screenY obtain the left margin and top margin of the click position relative to the screen, if the iframe factor is not taken into account, the performance in different browsers is still consistent.
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 obtain the coordinates of the mouse position relative to the browser window, the clientX of event, the clientY attribute indicates the left margin and top margin of the cursor position relative to the document. So we wrote such code.
function getMousePos(event) { var e = event || window.event; return {'x':e.clientX,'y':clientY} }
Relative document
There is no problem with a simple test, but clientX and clientY obtain the coordinates relative to the current screen, ignoring the Page scrolling factor, which is useful in many conditions, but what should we do when we need to consider Page scrolling, that is, the coordinates relative to the document (body element? Add the scroll displacement. Next we will try to calculate the page scroll displacement.
In fact, the problem in Firefox is much simpler, because Firefox supports pageX and pageY attributes, which have included Page scrolling.
Extends umentElement. scrollLeft, document.doc umentElement. 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 }; }
The above content is a series of methods for getting the mouse position based on JavaScript, I hope you will like it.