OffsetX/Y, clientX/Y concept
OffsetX /Y: The place where the event occurred is in the x and Y coordinates of the event source element’s coordinate system. The clientX/Y event property returns the horizontal/vertical coordinates of the mouse pointer to the *** browser page (or client area) *** when the event is triggered.
OffsetX/Y, clientX/Y
ClientX Sets or gets the x-coordinate of the mouse pointer position relative to the client area of the window, which excludes the controls and scrollbars of the window itself. ClientY sets or gets the y-coordinate of the mouse pointer position relative to the client area of the window, which excludes the controls and scrollbars of the window itself. OffsetX Sets or gets the x-coordinate of the mouse pointer position relative to the (this) object that triggered the event. OffsetY sets or gets the y-coordinate of the mouse pointer position relative to the (this) object that triggered the event. The above description is taken from the website
The code examples
HTML code:
<body>
<div class="butterfly" id="butterfly"></div>
</body>
Copy the code
The CSS code:
.butterfly {
position: relative;
width: 100px;
height: 100px;
background-color: pink;
}
Copy the code
JS code:
window.onload = function () { let fly = document.getElementById("butterfly") fly.onmousedown = function () { document.onmousemove = function (event) { fly.style.top = event.clientY + "px" fly.style.left = event.clientX + "px" console.log("offsetX" + event.offsetX) console.log("offsetY" + event.offsetY) console.log("clientX" + event.clientX) Console. log("clientY" + event.clienty) console.log("\n")}} Document.onmouseup = function () {document.onmousemove = null}}Copy the code
The screenshot of the above code running results is as follows:
We can see that the offsetX/Y value is always 0 no matter how the mouse moves. This is because the offsetX/Y value is relative to the coordinate system of the trigger event object (the box div in the code), and the div in the code always moves with the mouse, so the value is always 0.
Fly.onmousedown =function() has a default parameter event, which is the same as the document.onmousemove parameter event, so it refers to the same event object.
Change the js code to the following:
window.onload = function () {
document.onmousemove = function (event) {
console.log("offsetX" + event.offsetX)
console.log("offsetY" + event.offsetY)
console.log("clientX" + event.clientX)
console.log("clientY" + event.clientY)
console.log("\n")
}
}
Copy the code
The above code is captured as follows
We can see from the screenshot that offsetX/Y is always equal to clientX/Y because offsetX/Y is also relative to the browser edge.