有時候我們需要知道元素精確落在頁面的哪個座標,再據此做判斷或計算。例如線上調色板,就是靠滑鼠位置與元素位置比對,換算出對應的顏色值。
在 jQuery 中,取得元素位置有兩種方法:
offset();position()。offset() 用來「獲取」或「設置」元素相對於「當前文檔」(也就是瀏覽器視窗)的偏移距離。
語法:
$().offset().top; $().offset().left;
說明:
$().offset() 回傳一個座標物件,其中有兩個屬性:top 與 left。
$().offset().top 代表元素距離文檔「頂部」的距離,$().offset().left 代表距離文檔「左側」的距離。兩者回傳的都是純數字(不帶單位)。
舉例:
<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<title></title>
<style type="text/css">
body { text-align:center; }
#main { text-align:left; margin:100px auto; padding:15px; border:1px dashed gray; display:inline-block; }
#box1,#box2 { display:inline-block; height:100px; width:100px; }
#box1 { background-color:Red; }
#box2 { background-color:Orange; }
</style>
<script type="text/javascript" src="jquery-1.12.0.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btn").click(function () {
//獲取box2距離頂部的距離
var top = $("#box2").offset().top;
//獲取box2距離左部的距離
var left = $("#box2").offset().left;
var str = "box2與文檔頂部距離是:" + top + "\n" + "box2與文檔左部距離是:" + left;
alert(str);
})
})
</script>
</head>
<body>
<div id="main">
<div id="box1"></div><br />
<div id="box2"></div><br />
<input id="btn" type="button" value="獲取" />
</div>
</body>
</html>
在瀏覽器中預覽效果如下:
分析:
點擊「獲取」按鈕後,程式會讀取 id 為 box2 的元素相對文檔頂部與左側的距離,並用 alert 顯示出來。
position() 則是用來取得元素相對於「其被定位的祖輩元素」的偏移距離。
語法:
$().position().top $().position().left
說明:
$().position() 同樣回傳一個座標物件,包含 top 與 left 兩個屬性,數值皆為不帶單位的數字。top 是元素相對於定位祖先「頂部」的垂直距離,left 則是相對於「左側」的水平距離。
舉例:
<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<title></title>
<style type="text/css">
#father { position:relative; width:200px; height:200px; background-color:orange; }
#son { position:absolute; top:20px; left:50px; width:50px; height:50px; background-color:red; }
</style>
<script type="text/javascript" src="jquery-1.12.0.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btn").click(function () {
var top = $("#son").position().top;
var left = $("#son").position().left;
var str = "子元素相對父元素頂部距離是:" + top + "\n" + "子元素相對父元素左部距離是:" + left;
alert(str);
})
})
</script>
</head>
<body>
<div id="father">
<div id="son"></div>
</div>
<input id="btn" type="button" value="獲取" />
</body>
</html>
在瀏覽器中預覽效果如下:
分析:
點擊「獲取」之後,就能讀出子元素相對父元素的垂直與水平距離。這正好呼應 CSS 定位佈局裡那句口訣——「外相對,內絕對」:父元素設 position:relative,子元素用 position:absolute 定位,座標原點就落在父元素上。如果這個例子讓你卡住,建議先把 CSS 定位的基礎補牢再回來。
在實際的 Web 開發中,取得元素座標是非常頻繁的需求。把 offset() 與 position() 搭配使用,可以快速拿到我們需要的座標資訊,請務必熟練。後續章節我們會把這些技巧放進完整的實戰案例裡。