Home > Web Front-end > JS Tutorial > Use javascript to get the code of the mouse cursor position on the page and the object that triggered the event_javascript skills

Use javascript to get the code of the mouse cursor position on the page and the object that triggered the event_javascript skills

WBOY
Release: 2016-05-16 18:39:52
Original
1036 people have browsed it

Use javascript to get the mouse position:

Copy code The code is as follows:

function mousePosition(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
} ;
}

document.onmousemove = mouseMove;
function mouseMove(ev){
ev = ev || window.event;
var mousePos = mousePosition(ev);
}

Detailed description of the code has been introduced in the original text, now go here:
We must first declare an evnet object, which will be activated regardless of movement, click, key press, etc. For an evnet, in Internet Explorer, event is a global variable and will be stored in window.event. In firefox or other browsers, the event will be obtained by the corresponding function. When we assign the mouseMove function to document.onmousemove, mouseMove will get the mouse movement event.
In order for ev to obtain the event event in all browsers, "||window.event" will not work under Firefox because ev already has a value assigned. In MSIE ev is empty, so you get window.event .
Because we need to obtain the mouse position multiple times in this article, we designed a mousePosition function, which contains one parameter: event.
Because we are going to run under MSIE and other browsers, Firefox and other browsers use event.pageX and event.pageY to represent the position of the mouse relative to the document. If you have a 500*500 window and your mouse is in Absolutely in the middle, then the values ​​of pageX and pageY are both 250, and if you scroll down 500, then pageY will become 750.
MSIE is just the opposite. It uses event.clientX and event.clientY to indicate that the mouse is equivalent to the position of the window, not the document. In the same example, if you scroll down 500, clientY is still 250, so we need to add scrollLeft and scrollTop properties relative to the document. Finally, documents in MSIE do not start at 0,0, but usually have a small border (usually 2 pixels). The size of the border is defined in document.body.clientLeft and clientTop. We also add these.
Luckily, we have now solved the coordinate problem using the mousePosition function, so we don’t need to worry about it anymore.

Use javascript to get the object that triggered the event
Copy the code The code is as follows:

Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template