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


jQuery position() 方法

position() 方法獲取的元素相對於其偏移父級的頂部和 left 位置

返回的物件包含兩個整型屬性: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>

更新於:2019-12-10

已瀏覽 256 次

開啟您的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.