JavaScript's three ways to get the mouse position

In some DOM operations, we often deal with the position of the elements. Mouse interactive is a frequently used aspect. It is disappointing that different browsers will have different The result is even that there is no result under the browser. This article makes some simple summaries on the coordinates of the mouse click position.

Get the mouse position First, you need to know what is the event. Event is an object that declares a global variable. Under chrome and IE, you can access it at will. For the curious friend console.log event. but! ! ! There is no event object under Firefox! !

好消息 is: in IE8, chrome, there is event this object!

鼠标Click location coordinates

Relative to the screen

If it is related to the mouse click to determine the position is relatively simple, after getting the mouse click event, the event screenX, screenY gets the click position relative to the screen The left margin and the top margin, regardless of the iframe factor, are consistent under different browsers.

function getMousePos(event) {
      var e = event || window.event;
      return {'x':e.screenX,'y':screenY}
}

Relative to the browser window

simple code can be achieved, but this is not enough, because in most cases we want to get the coordinates of the mouse click position relative to the browser window, event clientX, clientY The attributes represent the left margin and the top margin of the mouse click position relative to the document.

function getMousePos(event) {
      var e = event || window.event;
      return {'x':e.clientX,'y':clientY}
}

Relative to the document

clientX and clientY are the coordinates relative to the current screen, ignoring the page scrolling factor, which is useful in many environments, but when we need to consider page scrolling, that is, relative to the document What should I do with the coordinates of the (body element)? Just add the displacement of the scroll.

In chrome, you can calculate the page scrolling displacement by document.body.scrollLeft, document.body.scrollTop, and in IE you can reprint the address by 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 };
}

复制代码

: http ://www.cnblogs.com/dolphinX/archive/2012/10/09/2717119.html