在 jQuery 中,jQuery.offsetParent( ) 與 jQuery.offset( ) 有何區別?
jQuery.offsetParent( ) 方法
offsetParent( ) 方法返回一個 jQuery 集合,該集合包含與第一個匹配元素的已定位的父級。
這是元素的具有位置(相對於相對或絕對)的第一個父級。此方法僅適用於可見元素。
示例
嘗試執行以下程式碼,以瞭解如何使用 jQuery 中的 jQuery.offsetParent() 和 jQuery.parent() 方法 −
<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 offset() 方法
offset( ) 方法獲取相對於文件的第一個匹配元素的當前偏移量(以畫素為單位)。
示例
嘗試執行以下程式碼,瞭解如何在 jQuery 中使用 offset() 方法-
<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>
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP