.offset()

Contents:

.offset() 官网原E文: Object

描述: 为匹配的元素集合中获取第一个元素的当前坐标,相对于文档(document)。

  • version added: 1.2.offset()

.offset()方法允许我们检索一个元素相对于文档(document)的当前位置。和.position()的差别在于:.position()是相对于相对于父级元素的位移。当定位在全局环境中(比如拖放的实现)最高的一个新元素时.offset()是非常有用的。

.offset()返回一个包含topleft属性的对象 。

注意:jQuery不支持获取隐藏元素的偏移坐标。

举例:

例子: 使用第二个段落的位置:

<!DOCTYPE html>
<html>
<head>
  <style>
p { margin-left:10px; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
  <p>Hello</p><p>2nd Paragraph</p>
<script>var p = $("p:last");
var offset = p.offset();
p.html( "left: " + offset.left + ", top: " + offset.top );</script>

</body>
</html>

Demo:

例子 点击查看位置。

<!DOCTYPE html>
<html>
<head>
  <style>
p { margin-left:10px; color:blue; width:200px; 
    cursor:pointer; }
span { color:red; cursor:pointer; }
div.abs { width:50px; height:50px; position:absolute;
          left:220px; top:35px; background-color:green; 
          cursor:pointer; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
  <div id="result">Click an element.</div>
<p>
  This is the best way to <span>find</span> an offset.
</p>

<div class="abs">
</div>
  
<script>
$("*", document.body).click(function (e) {
  var offset = $(this).offset();
  e.stopPropagation();
  $("#result").text(this.tagName + " coords ( " + offset.left + ", " +
                                  offset.top + " )");
});

</script>

</body>
</html>

Demo:

.offset( coordinates ) 官网原E文: jQuery

描述: 设置匹配的元素集合中每个元素的当前坐标,相对于文档(document)。

  • version added: 1.4.offset( coordinates )

    coordinates一个包含topleft属性的对象,用整数指明元素的新顶部和左边坐标。

  • version added: 1.4.offset( function(index, coords) )

    function(index, coords)返回用于设置坐标的一个函数。接收元素在匹配的元素集合中的索引位置作为第一个参数,和当前坐标作为第二个参数。这个函数应该返回一个包含topleft属性的对象。

.offset()方法允许我们重新设置元素的位置,这个元素的位置是相对于document对象的。如果对象原先的position样式属性是static的话,会被改成relative来实现重定位。

举例:

设置第二个段落的位置:

<!DOCTYPE html>
<html>
<head>
  <style>p { margin-left:10px; } </style>
  <script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
  <p>Hello</p><p>2nd Paragraph</p>
<script>$("p:last").offset({ top: 10, left: 30 });</script>

</body>
</html>

Demo:

jQuery 1.6 API 中文版Clove整理、修订