JQuery - .position不返回相对于父的偏移量 [英] JQuery - .position isn't returning offset relative to parent
问题描述
我使用 .position
来找到元素相对于父元素的偏移量,但是它似乎返回一个值,父对象的祖先树。
I'm using .position
to find the offset of where the element is relative to the parent, however it seems to be returning a value that is the offset from some parent up the ancestor tree.
我有一个按钮,它包装一个div和它的div的唯一元素。 div是浮动的。 .position
正在返回一个值如 {left:780,top:370}
{left:200,top:0}
。
I have a button, and its wrapped withing a div and its the only element of that div. The div is floated right. .position
is returning a value like {left:780, top:370}
, when the true value should be around {left:200, top:0}
.
我使用jquery 1.4
I'm using jquery 1.4
推荐答案
如果我是正确的,我认为这是一个CSS问题,不一定是一个jQuery的一个..
我的理解是,默认值的CSSposition属性是静态的(不是绝对的,相对的),并且相对于未设置为静态的第一个祖先计算定位。
If I am correct, I think this is a CSS issue, not necessarily a jQuery one.. My understanding is that the default value of the CSS "position" property is static (not absolute, relative), and positioning is calculated relative to the first ancestor that is not set to static.
没有具有非静态位置的祖先,元素将相对于html块定位。
If the element has no ancestor with non-static position, the element will be positioned relative to the html block.
如果要定位相对于包装器div的div,请尝试设置
If you want to position a div relative to a wrapper div, try setting the wrapper div's position property to something other than static (relative, absolute), depending on your needs.
下面是一个简单的例子来演示这个..
Here's a simple example that demonstrates this..
<html>
<style type="text/css">
.divOuter { border:1px solid Green; width:350px; height:50px; padding:2px; margin-left:80px; }
.divInner{border:1px solid Blue; width:200px; height:50px; padding:2px; position:absolute; left:100px;}
</style>
<body>
<div class="divOuter">
<div class="divInner">
positioned relative to html block
</div>
</div>
<div class="divOuter" style="position:relative;">
<div class="divInner">
positioned relative to parent div
</div>
</div>
</body>
</html>
这篇关于JQuery - .position不返回相对于父的偏移量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!