English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Sometimes, we need to get the distance of window dragging or mouse movement. In this case, you can get the desired result by calculating the position of the mouse before and after in the page. The following introduces several event properties:
1Client area coordinate position
Mouse events always occur at a specific location in the browser viewport. This location information is stored in the event object's clientX and clientY properties. Their values represent the horizontal and vertical coordinates of the mouse pointer in the viewport at the time of the event (excluding the distance the page has scrolled). As shown in the following figure:
var div = document.getElementById("myDiv"); //Get the element EventUtil.on(div, "click", function(event){ event = EventUtil.getEvent(event); alert("Screen coordinates: ") + event.screenX + "," + event.screenY); });
Note: In this case, EventUtil.on() refers to binding events to elements, and EventUtil.getEvent(event) refers to obtaining the event object. EventUtil is a custom event object (implemented using JavaScript), which contains some cross-browser methods. For the specific implementation, please refer to another article "Some Cross-Browser Event Methods". If the project uses jQuery plugins, you can replace them with the corresponding methods.
2Page coordinate position
The event object properties pageX and pageY can tell you where the event occurred in the page. In other words, these two properties represent the position of the mouse cursor in the page (equivalent to the position coordinates of the mouse in the window). + The distance the page has scrolled).
var div = document.getElementById("myDiv");//Get the element with id "myDiv" EventUtil.on(div, "click", function(event){//Bind click event to the element event = EventUtil.getEvent(event);//Get the event object var pageX = event.pageX,pageY = event.pageY; if (pageX === undefined){//IE8and earlier versions 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); });
3Screen coordinate position
You can determine the coordinate information of the mouse pointer relative to the entire screen at the time of the mouse event by using the screenX and screenY attributes. As shown in the following figure:
var div = document.getElementById("myDiv"); EventUtil.on(div, "click", function(event){ event = EventUtil.getEvent(event); alert("Screen coordinates: ") + event.screenX + "," + event.screenY); });
The article is referenced from 'Advanced JavaScript Design Third Edition'
Thank you for reading, I hope it can help you. Thank you for your support to this site!