jQuery offsetParent() 方法



jQuery 中的offsetParent() 方法用於獲取所選元素最近的已定位祖先元素。

您可以使用 jQuery 或利用 CSS position 屬性(例如 relative、absolute 或 fixed 定位)來定位元素。

語法

以下是 jQuery 中 offsetParent() 方法的語法:

$(selector).offsetParent()

引數

此方法不接受任何引數。

示例

在下面的示例中,我們使用 offsetParent() 方法來查詢<p> 元素最近的已定位父元素:

<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        // Find the offset parent of the p element
        const offsetParent = $("p").offsetParent();
            // Check if the offset parent exists
        if(offsetParent !== null) {
            // Set the background color of the offset parent to green
            offsetParent.css("background-color", "green");
            alert("offset parent found. It will now be highlighted with green color.");
        } else {
            alert("No offset parent found.");
        }
    });
});
</script>
</head>
<body>
<div style="border:1px solid black; width: 30%; position:absolute; left:10px; top:50px" >
   <div style="border:1px solid black; margin:50px; background-color:yellow">
      <p>Click on the above button to find and set background color for the first positioned parent element of this paragraph.</p>
   </div>
</div>
<button>Click here!</button>
</body>
</html>

執行上述程式後,如果我們點選按鈕,該方法會找出<p> 元素的 offsetParent,發出警報,並將背景顏色設定為綠色。

jquery_ref_traversing.htm
廣告