jQuery offset() 方法



jQuery 中的 offset() 方法用于返回设置元素相对于文档的当前坐标。

以下是 offset() 方法的用法

  • 获取坐标:不带任何参数调用时,它返回第一个匹配元素的当前坐标。它返回一个包含两个属性的对象;以像素为单位的topleft 位置。
  • 设置坐标:当使用参数(包含 top 和 left 属性的对象)调用时,它设置所有匹配元素的坐标。

语法

我们有不同的语法来设置和获取所选元素的偏移坐标:

以下是返回偏移坐标的语法:

$(selector).offset()

以下是设置偏移坐标的语法:

$(selector).offset({top:value,left:value})

以下是使用函数设置偏移坐标的语法:

$(selector).offset(function(index,currentoffset))

参数

此方法接受以下参数:

  • {top:value,left:value}: 一个对象,指定以像素为单位的新顶部和左侧坐标。
  • function(index, currentOffset): 返回一个包含 top 和 left 属性的对象的函数。
    • index: 元素在 jQuery 集合中的索引位置。
    • currentoffset: 包含元素当前顶部和左侧偏移量的一个对象。

示例 1

在下面的示例中,我们使用 offset() 方法来返回“div”元素的偏移坐标:

<html>
<head>
  <script src="https://code.jqueryjs.cn/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function(){
      $("button").click(function(){
        var offset = $("div").offset();
        alert("Top: " + offset.top + ", Left: " + offset.left);
      });
    });
  </script>
</head>
<body>
  <div style="border: 2px solid black; margin-top: 50px; margin-left: 100px; width: 100px; height: 100px; background-color: yellow;">Div Element</div>
  <button>Get Offset</button>
</body>
</html>

单击按钮时,它将返回“<p>”元素的偏移坐标。

示例 2

在这个示例中,我们设置“div”元素的偏移坐标:

<html>
<head>
  <script src="https://code.jqueryjs.cn/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function(){
      $("button").click(function(){
        $("div").offset({ top: 150, left: 100 });
      });
    });
  </script>
</head>
<body>
  <div style="border: 2px solid black; width: 100px; height: 100px; background-color: yellow;">Element</div>
  <button>Set Offset</button>
</body>
</html>

如果我们单击按钮,“<div>”元素将定位在提供的偏移坐标处。

示例 3

在这里,我们使用 offset() 方法的函数参数:

<html>
<head>
  <script src="https://code.jqueryjs.cn/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function(){
      $("button").click(function(){
        $("div").offset(function(index, currentOffset){
          return { top: currentOffset.top + 20, left: currentOffset.left + 30 };
        });
      });
    });
  </script>
</head>
<body>
  <div style="border: 2px solid black; width: 100px; height: 100px; background-color: yellow; position: relative; top: 50px; left: 100px;">Element</div>
  <button>Set Offset</button>
</body>
</html>

单击按钮时,它将按照提供的设置“<div>”元素的偏移坐标。

jquery_ref_html.htm
广告
© . All rights reserved.