加载中...

offset()


概述    .offset()

返回值:Object

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

  • V : 1.2.offset()

    • 这个方法不接受任何参数

.offset()方法允许我们检索一个元素相对于文档(document)的当前位置。和.position()的差别在于:.position()是相对于相对于父级元素的位移。当通过全局操作(特别是通过拖拽操作)将一个新的元素放置到另一个已经存在的元素的上面时,若要取得这个新的元素的位置,那么使用 .offset() 更合适。

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

注意:jQuery不支持获取隐藏元素的偏移坐标。同样的,也无法取得隐藏元素的 border, margin, 或 padding 信息。

若元素的属性设置的是 visibility:hidden,那么我们依然可以取得它的坐标。但是若设置的属性是 display:none,由于在绘制 DOM 树时根本就不绘制该元素,所以它的位置属性值是 undefined。

示例

实例

使用第二个段落的位置:

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <style>
  5. p { margin-left:10px; }
  6. </style>
  7. <script src="http://code.jquery.com/jquery-latest.js"></script>
  8. </head>
  9. <body>
  10. <p>Hello</p><p>2nd Paragraph</p>
  11. <script>var p = $("p:last");
  12. var offset = p.offset();
  13. p.html( "left: " + offset.left + ", top: " + offset.top );</script>
  14. </body>
  15. </html>

运行一下

实例

点击查看位置。

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <style>
  5. p { margin-left:10px; color:blue; width:200px;
  6. cursor:pointer; }
  7. span { color:red; cursor:pointer; }
  8. div.abs { width:50px; height:50px; position:absolute;
  9. left:220px; top:35px; background-color:green;
  10. cursor:pointer; }
  11. </style>
  12. <script src="http://code.jquery.com/jquery-latest.js"></script>
  13. </head>
  14. <body>
  15. <div id="result">Click an element.</div>
  16. <p>
  17. This is the best way to <span>find</span> an offset.
  18. </p>
  19. <div class="abs">
  20. </div>
  21. <script>
  22. $("*", document.body).click(function (e) {
  23. var offset = $(this).offset();
  24. e.stopPropagation();
  25. $("#result").text(this.tagName + " coords ( " + offset.left + ", " +
  26. offset.top + " )");
  27. });
  28. </script>
  29. </body>
  30. </html>

运行一下

概述    .offset( coordinates )

返回值:jQuery

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

  • V : 1.4.offset( coordinates )

    • coordinates
      类型: PlainObject
      一个包含topleft属性的对象,用整数指明元素的新顶部和左边坐标。
  • V : 1.4.offset( function(index, coords) )

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

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

示例

实例

设置第二个段落的位置:

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

运行一下


还没有评论.