在 jQuery 中,jQuery.offsetParent() 方法和 jQuery.parent() 方法有什麼區別?


jQuery.offsetParent()

offsetParent() 方法返回一個 jQuery 集合,其中包含第一個匹配元素的定位父元素。

這是元素的第一個具有定位(例如相對或絕對)的父元素。此方法僅適用於可見元素。

示例

您可以嘗試執行以下程式碼,學習如何在 jQuery 中使用 jQuery.offsetParent()。

線上演示

<html>

   <head>
      <title>jQuery offsetParent() 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).offsetParent();
               $("#lresult").html("left offset: <span>" +
                  offset.offset().left + "</span>.");
               $("#tresult").html("top offset: <span>" +
                  offset.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  style = "background-color:pink;"></div>
      </div>
 
      <div  style = "background-color:#123456;">
         <div  style = "background-color:#f11;"></div>
      </div>

   </body>
</html>

jQuery.parent()

jQuery.parent() 方法用於返回所選元素的直接父元素。它只有一個引數:

序號
引數
描述
1
filter
設定父級搜尋的選擇器表示式。此引數是可選的。

示例

您可以嘗試執行以下程式碼,學習如何使用 jQuery.parent() 函式:

線上演示

<!DOCTYPE html>
<html>
<head>
<style>
.myclass * {
    display: block;
    border: 2px solid blue;
    color: red;
    padding: 10px;
    margin: 8px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("span").parent().css({"color": "green", "border": "3px solid yellow"});
});
</script>
</head>

<body class="myclass">body
  <div style="width:500px;">div
    <ol>ol
      <li>li - This is the direct parent element
        <span>span</span>
      </li>
    </ol>  
  </div>
</body>

</html>

更新於: 2020年2月14日

255 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告