DIV CSS 佈局教程網

jQuery position():取得元素相對於定位父元素的距離
編輯:JQuery常見問題     

可以先看看效果:https:///keleyi/phtml/jquery/6.htm

position() 回傳的是元素相對於它第一個 position 為 relative(或其他非 static)的父元素的偏移,包含 top 與 left 兩個整數屬性。這和 offset() 的「相對於文件」是兩套不同的座標系。

完整代碼

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<title>jquery獲取div等元素的相對位置 -</title>
<script type="text/javascript" src="https:///keleyi/pmedia/jquery-1.9.1.min.js"></script>
</head>
<body>
<div style="position:relative;padding:10px;border:solid 1px green;">
<div style="padding:26px 50px 30px 35px;border:solid 1px black;position:static;">
<div id="keleyi_com" style="width:500px;border:1px solid silver;height:120px">本DIV的id為keleyi_com;</div>
</div>
</div>
<div id="tips_keleyi_com"></div>
<script type="text/javascript">
$(document).ready(function () {
  var position = $("#keleyi_com").position();
  $("#tips_keleyi_com").text("與它的第一個 position 為 relative 的父元素的相對位置為:距頂部" + position.top + ",距左邊" + position.left);
})
</script>
</body>
</html>

這個示例的巧妙之處

結構刻意設計成三層:最外層是 position:relative 且帶 10px padding,中間層是 position:static 但有大內距,最內層才是目標。因為中間層是 static,position() 會跳過它,直接以最外層為參考點。因此回傳的 top、left 會把中間層的 26px、35px padding 一併計入,這正好說明了「offsetParent 是最近的定位祖先,而不是直接父元素」。

什麼時候用哪個

  • 要把元素放到畫面某個絕對位置(例如跟隨捲動的浮動層)→ 用 offset()。
  • 要在某個 relative 容器內部排版、計算子元素之間的間距 → 用 position()。

原文:https:///a/bjac/lgg5u5qk.htm

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved