Capturing Mouse Movement

来源:百度文库 编辑:神马文学网 时间:2024/05/17 06:28:44
To start we need to capture the mouse coordinates. This is done by adding a function to document.onmousemove:
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
};
}
Demo - Move your mouseMouse X Position:   Mouse Y Position:
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 MSIE ev is null so it will get set to window.event.
Since we‘ill 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 MSIE 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 500x500 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, MSIE 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 500x500 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 MSIE 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 haveto worry about this again.