.position()

.position()

.position()Returns: Object

Description: Get the current coordinates of the first element in the set of matched elements, relative to the offset parent.

  • version added: 1.2.position()

    • This method does not accept any arguments.

The .position() method allows us to retrieve the current position of an element relative to the offset parent. Contrast this with .offset(), which retrieves the current position relative to the document. When positioning a new element near another one and within the same containing DOM element, .position() is the more useful.

Returns an object containing the properties top and left.

Note: jQuery does not support getting the position coordinates of hidden elements or accounting for borders, margins, or padding set on the body element.

Additional Notes:

  • The number returned by dimensions-related APIs, including .position(), may be fractional in some cases. Code should not assume it is an integer. Also, dimensions may be incorrect when the page is zoomed by the user; browsers do not expose an API to detect this condition.

Example:

Access the position of the second paragraph:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>position demo</title>
  <style>
  div {
    padding: 15px;
  }
  p {
    margin-left: 10px;
  }
  </style>
  <script src="https://code.jquery.com/jquery-1.10.2.js" rel="external nofollow" ></script>
</head>
<body>
 
<div>
  <p>Hello</p>
</div>
<p></p>
 
<script>
var p = $( "p:first" );
var position = p.position();
$( "p:last" ).text( "left: " + position.left + ", top: " + position.top );
</script>
 
</body>
</html>

Demo:

© The jQuery Foundation and other contributors
Licensed under the MIT License.
https://api.jquery.com/position

在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号

意见反馈
返回顶部