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>
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP