[英]Why does the position method not return the expected values?
在這種情況下,為什么position
方法不返回[left: 100, top: 10]
:
<!DOCTYPE HTML>
<html>
<head>
<style>
#parent1 {
width: 300px;
height: 200px;
border: solid 9px pink;
}
#child1 {
position: relative;
left: 100px;
top: 10px;
width: 100px;
height: 100px;
border: solid 5px green;
}
</style>
<script src="http://jquery-local/jquery.all.js"></script>
<script type="text/javascript">
(function ($) {
$(document).ready(function () {
console.log($('#child1').position());
});
})(jQuery);
</script>
</head>
<body>
<div id="parent1">
<div id="child1"></div>
</div>
</body>
</html>
是通過css
方法獲得 position 的唯一方法嗎?
您的 jquery 源位置錯誤。
嘗試將 jquery src 更改為http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js
或到最新版本http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js
為我工作 - 在這個 JSFiddle中,我得到
left: 119
top: 19
它占頂部的 10px 值加上周圍元素的 9px 邊框。
但是, position()
可能不是您想要的 - 它檢索 position相對於偏移父級。 在這種情況下,它沒有區別,因為沒有偏移父級,但是如果您想要文檔中的 position,請改用.offset()
。
對我來說,它返回:[117, 27]。
首先,因為子節點的 position 是相對於父節點的,所以子節點的坐標僅與父節點的坐標相對。 這意味着父級的任何定位,例如默認的正文邊距,都會添加到子級的定位中。 此外,還添加了父級的邊框,另外 9 像素。 如果設置body的margin為0,則孩子的position為[109, 19]:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.