jQuery 中的 jQuery.position() 和 jQuery.offset() 有什麼區別?


jQuery 的 position() 方法

position() 方法將獲取相對於其偏移父級指定元素的頂部和左側位置。

返回的物件包含兩個整數屬性 top 和 left。為確保準確計算,需要對邊距、邊框和填充使用畫素值。此方法僅適用於可見元素。

示例

嘗試執行以下程式碼段以瞭解如何在 jQuery 中使用 position() 方法

線上演示

<html>

   <head>
      <title>The jQuery Example</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
       
      <script>
         $(document).ready(function() {
           
            $("div").click(function () {
               var position = $(this).position();
               $("#lresult").html("left position: <span>" + position.left + "</span>.");
               $("#tresult").html("top position: <span>" + position.top + "</span>.");
            });
               
         });
      </script>
       
      <style>
         div {
             width:60px;
             height:60px;
             margin:5px;
             float:left;
         }
      </style>
   </head>
   
   <body>
   
      <p>Click on any square:</p>
      <span id = "lresult"> </span>
      <span id = "tresult"> </span>
       
      <div  style = "background-color:blue;"></div>
      <div  style = "background-color:pink;"></div>
      <div  style = "background-color:#123456;"></div>
      <div  style = "background-color:#f11;"></div>
       
   </body>
</html>

jQuery 的 offset() 方法

offset() 方法將獲取第一個匹配元素的當前偏移量(以畫素為單位),相對於文件。

示例

嘗試執行以下程式碼段以瞭解如何在 jQuery 中使用 offset() 方法

線上演示

jQuery position() method
<html>

   <head>
      <title>jQuery offset() method</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
       
      <script>
         $(document).ready(function() {
           
            $("div").click(function () {
               var offset = $(this).offset();
               $("#lresult").html("left offset: <span>" + offset.left + "</span>.");
               $("#tresult").html("top offset: <span>" + offset.top + "</span>.");
            });
               
         });
      </script>
       
      <style>
         div { width:60px; height:60px; margin:5px; float:left; }
      </style>
   </head>
   
   <body>
   
      <p>Click on any square:</p>
      <span id = "lresult"> </span>
      <span id = "tresult"> </span>
       
      <div style = "background-color:blue;"></div>
      <div style = "background-color:pink;"></div>
      <div style = "background-color:#123456;"></div>
      <div style = "background-color:#f11;"></div>
       
   </body>
</html>

更新於: 10-Dec-2019

256 次瀏覽

開啟你的 職業之旅

完成課程以獲得認證

開始學習
廣告