我想获取元素相对于其父元素的位置。因此,对于这个我使用jquery position function
我创建了一个JsFiddle.如何访问元素相对于其父元素的位置
在这拨弄我正在访问#child
元素的top & left
位置。它应该返回top : 0 and left : 0
,因为它是#p
元素的子元素,它的位置是相对的,但它返回top : 223px and left : 1px
。谁能帮帮我吗 ?
我想获取元素相对于其父元素的位置。因此,对于这个我使用jquery position function
我创建了一个JsFiddle.如何访问元素相对于其父元素的位置
在这拨弄我正在访问#child
元素的top & left
位置。它应该返回top : 0 and left : 0
,因为它是#p
元素的子元素,它的位置是相对的,但它返回top : 223px and left : 1px
。谁能帮帮我吗 ?
这里是调整 问题是你没有指定父母的位置作为亲属。所以孩子立场是相对于计算出身体
<style type="text/css">
#gp {
width: 500px;
height: 200px;
margin: 0;
border: 1px solid black;
background-color:gray;
overflow:hidden;
}
#p {
width: 600px;
height: auto;
float: left;
position: relative;
}
#child{
position: relative;
}
</style>
<div id="gp">
<div id="p">
<div id="child">
</div>
</div>
</div>
jQuery(document).ready(function(){
alert($("#child").position().top + " " + $("#child").position().left);
});
也许是这样的:
function relative_pos(node) {
var parentOf = $(node).parent().offset();
var child = $(node).offset();
return {top: child.top - parentOf.top, left: child.left - parentOf.left};
}
console.log(relative_pos("#child"));
如果你不想改变你的CSS架构,来看看我的! – MyBoon