This article analyzes the method of obtaining the mouse coordinate position using JS. Share it with everyone for your reference, the details are as follows:
The coordinate positions of the mouse are as follows: the coordinate position of the mouse in the viewport (clientX, clientY), the coordinate position of the mouse on the page (pageX, pageY), the coordinate position of the mouse on the screen (screenX, screenY), where the mouse is in The coordinate position of the viewport (clientX, clientY) and the coordinate position of the mouse on the screen (screenX, screenY) are supported in all browsers, but the coordinate position of the mouse on the page (pageX, pageY) is supported in IE8 and earlier versions. It is not supported, but it doesn't matter. The values of pageX and pageY can be calculated through scrollLeft and scrollTop.
The first is the cross-browser event object
var EventUtil = { addHandler:function(elem,type,handler){ if(elem.addEventListener) { elem.addEventListener(type,handler,false); }else if(elem.attachEvent) { elem.attachEvent("on"+type,handler); }else { elem["on"+type]=handler; } }, removeHandler:function(elem,type,handler){ if(elem.removeEventListener) { elem.removeEventListener(type,handler,false); }else if(elem.detachEvent) { elem.detachEvent("on"+type,handler); }else { elem["on"+type]=null; } }, getEvent:function(event){ return event?event:window.event; }, getTarget:function(event){ return event.target||event.srcElement; }, preventDefault:function(event){ if(event,preventDefault){ event.preventDefault(); }else{ event.returnValue = false; } }, stopPropagation:function(event){ if(event.stopPropagation){ event.stopPropagation(); }else{ event.cancelBubble=true; } } };
1. Viewport coordinate position
var div = document.getElementById("myDiv"); EventUtil.addHandler(div,"click",function(event){ event = EventUtil.getEvent(event); alert("Client coordinages: "+event.clientX+","+event.clientY); });
2.Screen coordinate position
var div = document.getElementById("myDiv"); EventUtil.addHandler(div,"click",function(event){ event = EventUtil.getEvent(event); alert("Screen coordinates: "+event.screenX+","+event.screenY); });
3. Page coordinate location
var div = document.getElementById("myDiv"); EventUtil(div,"click",function(event){ event = EventUtil.getEvent(event); var pageX = event.pageX; var pageY = event.pageY; if(pageX==undefined) { pageX=event.clientX+document.body.scrollLeft||document.documentElement.scrollLeft; } if(pageY==undefined) { pageY = event.clientY+document.body.scrollTop||document.documentElement.scrollTop; } alert("Page coordinates: "+pageX+","+pageY); });
Readers who are interested in more content related to JavaScript mouse operation can check out the special topic of this site: " Summary of JavaScript mouse operation skills"
I hope this article will be helpful to everyone in JavaScript programming.