• 首页
  • vue
  • TypeScript
  • JavaScript
  • scss
  • css3
  • html5
  • php
  • MySQL
  • redis
  • jQuery
  • offset()

    在匹配的元素集合中,获取的第一个元素的当前坐标,或设置每一个元素的坐标,坐标相对于文档。

    .offset()
    • offset()
    .offset(coordinates)
    • offset(coordinates)
    • offset(function(index, coords))

    offset()

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

    .offset()
    • 这个方法不接受任何参数

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

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

    注意:jQuery不支持获取隐藏元素的偏移坐标。也不支持计算设置在<html>文档元素上的边距(margin)。

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

    例子

    使用第二个段落的位置:

    <!DOCTYPE html>
    <html>
    <head>
    <style>
    p { margin-left:10px; }
    </style><script src="https://www.lanmper.cn/static/js/jquery-3.5.0.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>
    

    Hello

    2nd Paragraph

    点击查看位置。

    <!DOCTYPE html>
    <html>
    <head>
    <style>
    p { margin-left:10px; color:blue; width:300px;cursor:pointer; }
    span { color:red; cursor:pointer; }
    div.abs { width:50px; height:50px; position:absolute;left:220px;text-align:center;background-color:green;cursor:pointer; }
    </style>
    <script src="https://www.lanmper.cn/static/js/jquery-3.5.0.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>
    
    Click an element.

    This is the best way to find an offset.

    div

    offset(coordinates)

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

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

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

    例子

    设置第二个段落的位置:

    <!DOCTYPE html>
    <html>
    <head>
      <style>p { margin-left:10px; } </style>
      <script src="https://www.lanmper.cn/static/js/jquery-3.5.0.js"></script>
    </head>
    <body>
      <p>Hello</p><p>2nd Paragraph</p>
    <script>$("p:last").offset({ left: 150 });</script>
     
    </body>
    </html>
    

    Hello

    2nd Paragraph

    上篇:position()

    下篇:offsetParent()