[英]Relative position of Div in another Div
How do I get the position of a Div relatively to its parent Div? 如何获得Div相对于其父Div的位置? Using
.position()
and .offset()
always gives me its position to the document. 使用
.position()
和.offset()
总是让我知道它在文档中的位置。
HTML: HTML:
<div id="frame">
<div id="inner"></div>
</div>
CSS: CSS:
Let's assume frame
is centered with margin: auto;
假设
frame
以margin: auto;
为中心margin: auto;
and width: 1024px
. 和
width: 1024px
。
inner
has left: 300px;
inner
left: 300px;
, top: 200px
and position: relative;
,
top: 200px
, position: relative;
. 。
What I want: 我想要的是:
A nice function for getting inners
's position data 300
and 200
(eg without px
when using .css('left')
etc. 一个很好的函数,用于获取
inners
位置数据300
和200
(例如,使用.css('left')
等时不带px
.css('left')
。
Is there anything? 有没有什么?
If you give the parent a "position" of "relative", then using .position()
should be its position inside of the parent. 如果给父对象一个“相对”的“位置”,则应使用
.position()
作为它在父对象内部的位置。
Using .offset
actually should always give you its position based off the document
, while using .position
gives you its "position" based off its first parent whose "position" is not "static" (default). 实际上,使用
.offset
始终应根据document
其位置,而使用.position
可以根据其“位置”不是“静态”(默认值)的第一个父项为其提供“位置”。
Here's examples: 例子如下:
http://jsfiddle.net/Z2VNx/ http://jsfiddle.net/Z2VNx/
http://jsfiddle.net/Z2VNx/1/ http://jsfiddle.net/Z2VNx/1/
The first example uses <br />
to add space at the top of the container, while the second example uses padding-top
to add space at the top of the container. 第一个示例使用
<br />
在容器顶部添加空间,而第二个示例使用padding-top
在容器padding-top
添加空间。 Both return a value greater than 0
for the child's top
position. 两者都返回一个大于
0
的值作为孩子的top
排名。
The only problem is that position
does not account for the child's margins, padding, and borders when calculating its position. 唯一的问题是,
position
在计算孩子的position
并未考虑孩子的边距,边距和边框。 This is because all of those are part of the element, so even though you may not visually see them, they wouldn't be included in the element's position calculation. 这是因为所有这些都是元素的一部分,因此即使您可能看不到它们,也不会将它们包含在元素的位置计算中。 So of course, depending on exactly what part of the element you want to see its position of, you need to add that to the result of
.position
. 因此,当然,根据要查看元素位置的确切位置,需要将其添加到
.position
结果中。 Some people want the "position" to return to top-left position of the border, which would mean adding the margin. 某些人希望“位置”返回到边框的左上角位置,这意味着要增加边距。 Something like this:
像这样:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.