HTML mouse coordinates and element coordinates, html mouse coordinate Elements
In this article, we will introduce the mouse coordinates, element coordinates, and the coordinates of the mouse in the specified element.
1. mouse coordinates
When mouse-related events (such as click and mousemove) are triggered, the coordinates of the current mouse can be obtained through the event object.
The obtained coordinates can be divided into two types:
1) MouseEvent.ScreenX, MouseEvent.ScreenY: Based on the X and Y coordinates of the screen, start from 0 to 0 in the upper left corner of the screen.
2) MouseEvent.ClientX, MouseEvent.ClientY: The X and Y coordinates based on the body.CurrentThe upper left corner of the body is the starting point of 0. If the body contains a horizontal or vertical scroll bar, the upper left corner is still the coordinate point of 0.
2. Element coordinates
ElementGetBoundingClientRect() Method to obtainClientRectObject that describes the orientation and width of an element.
2.1 ClientRect Object Attributes
Attribute name |
Attribute description |
Width |
Element width |
Height |
Element height |
Left |
Width between the upper left corner of the element and the current visible body |
Top |
The height from the upper left corner of the element to the current visible body |
Right |
The width from the bottom right corner of the element to the current visible body; right = left + width |
Bottom |
Height from the bottom right corner of the element to the current visible body; bottom = top + height |
2.2 illustration
2.3 other coordinates
In addition to these direct attributes, you can use other elements to obtain more detailed coordinates:
1) in the upper left corner of the elementHorizontal coordinates of the whole body= Document. body. scrollLeft + element. getBoundingClientRect (). left;
2) in the upper left corner of the elementVertical coordinates of the entire body= Document. body. scrollTop + element. getBoundingClientRect (). top;
3. coordinates of the mouse in the element
After obtaining the mouse and element coordinates, You can further obtain the coordinates of the mouse in the element.
Take the x coordinate of the mouse in the element as an example. equal to the left placed by the clientX of the mouse minus the getBoundingClientRect () of the element, the scrollLeft value of the element is added.
The formula is as follows::
X= Mouse. clientX-element. left + element. scrollLeft
Y= Mouse. clientY-element. top + element. scrollTop
Example
====================================== Series of articles ==============================================
This article: 1.7 HTML mouse coordinates and element coordinates
Web development path Series