jquery gets the position of the current element, and it is relative to the position of the document. We can use the jQuery offset() method to achieve this. The offset() method only works on visible elements.
Below we combine simple code to introduce to you how jquery gets the position of the current element.
The code example is as follows:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>jquery获取当前元素的位置</title> <style type="text/css"> *{ margin:0; padding:0; } #box{ width:150px; height:100px; background: orange; margin: 150px 100px; } </style> <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script> <script type="text/javascript"> $(function() { $("button").click(function(){ var offset = $("#box").offset(); alert("盒子的当前位置为: (left: " + offset.left + ", top: " + offset.top + ")"); }); }); </script> </head> <body> <button type="button">获取位置</button> </body> </html>
offset() method returns or sets the offset (position) of the matching element relative to the document.
The .offset() method allows us to retrieve the current position of an element relative to the document (specifically its bounding box, which excludes margins). Contrast this with .position(), which retrieves the current position relative to the offset parent. .offset() is more useful when doing global operations (especially implementing drag and drop) when placing a new element on top of an existing element.
.offset() returns an object containing attributes top and left.
Get the position of the current element, the result is as follows:
This article is about jquery method of getting the position of the current element, it is also very simple, I hope Help those in need!
The above is the detailed content of How to get the position of the current element in jquery. For more information, please follow other related articles on the PHP Chinese website!