Use javascript to get the mouse position:
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
Latest Articles by Author
-
2024-10-22 09:46:29
-
2024-10-13 13:53:41
-
2024-10-12 12:15:51
-
2024-10-11 22:47:31
-
2024-10-11 19:36:51
-
2024-10-11 15:50:41
-
2024-10-11 15:07:41
-
2024-10-11 14:21:21
-
2024-10-11 12:59:11
-
2024-10-11 12:17:31