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.jquery.com/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.jquery.com/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.jquery.com/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.