In some DOM operations, we often deal with the position of elements. Mouse interaction is a frequently used aspect. What is disappointing is that different browsers will have different results and even some browsers may not. As a result, this article makes some simple summaries on obtaining the mouse click position coordinates. There is no special statement that the code is tested and compatible under IE8, FireFox, and Chrome
Mouse click position coordinates
relative to screen
If it involves a mouse click to determine the position, it is relatively simple. After obtaining the mouse click event, the events screenX and screenY obtain the click position relative to the left margin and top margin of the screen. Iframe factors are not considered. Different browsers The performance is fairly consistent.
function getMousePos(event) { var e = event || window.event; return {'x':e.screenX,'y':screenY} }
Relative to 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 click position relative to the browser window. The clientX and clientY attributes of the event respectively represent the coordinates of the mouse click position relative to the document. Left margin, top margin. So similarly we wrote code like this
function getMousePos(event) { var e = event || window.event; return {'x':e.clientX,'y':clientY} }
Relative Document
There is no problem with simple tests, but clientX and clientY obtain coordinates relative to the current screen, ignoring page scrolling factors. This is useful under many conditions, but when we need to consider page scrolling, that is, relative to the document ( What should I do if the coordinates of the body element) are determined? Just add the scrolling displacement. Next we try to calculate the scrolling displacement of the page.
In fact, the problem will be much simpler under Firefox, because Firefox supports the attributes pageX and pageY, which already take page scrolling into account.
In Chrome, the page scrolling displacement can be calculated through document.body.scrollLeft and document.body.scrollTop, while in IE, it can be calculated through document.documentElement.scrollLeft and 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 }; }
The above content is the various methods of obtaining the mouse position based on JavaScript introduced by the editor. I hope you like it.