0. Credit to:
I. mouse event positon
- https://www.w3schools.com/jsref/event_clientx.asp
event.clientX: distance to the left border of viewport (position:fixed)event.screenX: distance to the left border of browserevent.pageX: distance to the left border of document area(position: absolute)
1 |
|
II. element position
getBoundingClientRect():top– Y-coordinate for the top element edge,left– X-coordinate for the left element edge,right– X-coordinate for the right element edge,bottom– Y-coordinate for the bottom element edge.
clientHeight: the height of the elementoffsetTop: returns the top position (in pixels) relative to the top of the offsetParent element. The returned value includes:- the top position, and margin of the element
- the top padding, scrollbar and border of the offsetParent element
- The offsetParent element is the nearest ancestor that has a position other than static.
(clientX,clientY): window coordinates, correspond toposition:fixed,(pageX,pageY): document coordinates , correspond toposition:absoluteformular:
pageY=clientY+ height of the scrolled-out vertical part of the document.pageX=clientX+ width of the scrolled-out horizontal part of the document.
1 | // get document coordinates of the element |
III. Summary
Any point on the page has coordinates:
- Relative to the window –
elem.getBoundingClientRect(). - Relative to the document –
elem.getBoundingClientRect()plus the current page scroll.
Window coordinates are great to use with position:fixed, and document coordinates do well with position:absolute.
Both coordinate systems have their “pro” and “contra”, there are times we need one or the other one, just like CSS position absolute and fixed.