About document.onmousemove

Posted on

referenc:How to drag and drop in javascript
document.onmousemove = mouseMove;

function mouseMove(ev){
ev = ev || window.event;
var mousePos = mouseCoords(ev);

function mouseCoords(ev){
if(ev.pageX || ev.pageY){
return {x:ev.pageX, y:ev.pageY};
return {
x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
y:ev.clientY + document.body.scrollTop - document.body.clientTop

We must first explain the event object. Whenever you move the mouse, click, press a key, etc., an event is fired. in Internet Explorer this event is global; it’s stored in window.event. In Firefox, and other browsers, this event is passed to whatever function is attached to the action. Since we attached the mouseMove function to document.onmousemove, mouseMove gets passed the event object.

To make ev contain the event object in every browser we OR it with window.event. In Firefox the " || window.event" will be ignored since ev already contains the event. In IE ev is null so it will get set to window.event.

Since we’ll need to obtain the mouse coordinates many times over this article we make a mouseCoords function that takes one argument: the event.

Again we run into differences between IE and other browsers. Firefox and other browsers use event.pageX and event.pageY to represent the mouse position relative to the document. If you have a 500×500 window and your mouse is in the middle, pageX and pageY will both be 250. If you then scroll down 500 pixels pageY will now by 750.

Contrary to this, IE decided to use event.clientX and event.clientY to represent the mouse position relative to the window, not the document. In our same example clientX and clientY will both be 250 if you put your mouse at the middle of a 500×500 window. If you scroll down on the page, clientY will remain 250 since it is measured relative to the window and not where you are on the document. As a result we need to add the scrollLeft and scrollTop properties of the document body to our mouse position. Finally, the document in IE isn’t actually at the 0,0 position. There is a small (usually 2px) border surrounding it. document.body.clientLeft and clientTop countain the width of this border, so we add those also to our mouse position.

Fortunately since we now have our mouseCoords function we don’t have to worry about this again.




WordPress.com Logo

您的留言將使用 WordPress.com 帳號。 登出 / 變更 )

Twitter picture

您的留言將使用 Twitter 帳號。 登出 / 變更 )


您的留言將使用 Facebook 帳號。 登出 / 變更 )

Google+ photo

您的留言將使用 Google+ 帳號。 登出 / 變更 )

連結到 %s