Home >Web Front-end >JS Tutorial >jQuery get coordinates of element
jQuery provides a variety of ways to obtain coordinate information of elements.
1. .position()
Method: Get the coordinates of the element offsetting the parent element relative to its . Offset parent element refers to the nearest ancestor element with a non-static
positioning method.
<code class="language-javascript">var pos = $('#wrapper').position(); console.dir(pos); // 输出:left: 0, top: 20</code>
2. .offset()
Method: Get the coordinates of an element relative to the document.
<code class="language-javascript">var offset = $('#wrapper').offset(); console.dir(offset); // 输出:left: 70, top: 40</code>
3. Get the coordinates directly: Combined with the method, the .offset()
and left
attributes are directly extracted. top
<code class="language-javascript">var elem = $("#wrapper"); var x = elem.offset().left; var y = elem.offset().top; console.log('x: ' + x + ' y: ' + y); // 输出:x: 70 y: 40</code>
4. Custom Function:getCoord()
Encapsulate a custom function to make the code more concise and easy to read.
<code class="language-javascript">jQuery.fn.getCoord = function() { var elem = $(this); var x = elem.offset().left; var y = elem.offset().top; console.log('x: ' + x + ' y: ' + y); // 输出:x: 70 y: 40 return { "x": x, "y": y }; }; $('#wrapper').getCoord(); // 输出:Object { x: 70, y: 40 }</code>
Note: The function is not efficient because it interrupts jQuery chain operations. getCoord()
Q1: How to use jQuery to get the coordinates of an element relative to a document?
Use the method. This method returns an object containing .offset()
and top
properties, respectively, representing the vertical and horizontal positions of an element relative to the document. left
<code class="language-javascript">var position = $("#element").offset(); console.log("元素位于: " + position.left + ", " + position.top);</code>
Q2: What is the difference between and .position()
methods in jQuery? .offset()
Returns the coordinates of an element relative to its offset parent element; .position()
Returns the coordinates of an element relative to the document. .offset()
Q3: How to set the coordinates of an element using jQuery?
Use the method to combine an object containing the .offset()
and top
attributes. left
<code class="language-javascript">$("#element").offset({ top: 100, left: 200 });</code>
Q4: How to use jQuery to get the absolute coordinates of an element?
Use the method to get the absolute coordinates of the element (relative to the document). .offset()
Q5: How to use jQuery to get the coordinates of an element relative to its parent element?
Use the method. .position()
The above is the detailed content of jQuery get coordinates of element. For more information, please follow other related articles on the PHP Chinese website!