简体   繁体   English

Div在另一个Div中的相对位置

[英]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; 假设framemargin: auto;为中心margin: auto; and width: 1024px . width: 1024px

inner has left: 300px; inner left: 300px; , top: 200px and position: relative; top: 200pxposition: 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位置数据300200 (例如,使用.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: 像这样:

http://jsfiddle.net/Z2VNx/2/ http://jsfiddle.net/Z2VNx/2/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM