我有一个棘手的问题,我拼命想找到一个工作解决方案。位置元素相对于JS中的parent.parent容器?没有绝对/固定的定位?
A article#post
和aside#sidebar
是左侧并排 - 很简单。 在我的article#post
里面是h1
和div.post-entry
。
我想知道我是否能以某种方式确定div.post-entry
与外部容器section#content
的相对偏移量。我想这样做的原因是,我可以在浮动边栏上放置与'div.post-entry`相同高度的margin-top
。
这里是我当前的HTML结构模型:
<section id="content">
<article id="post">
<h1>Title of the post</h1>
<div class="post-entry">
<p>Something</p>
</div>
</article>
<aside id="sidebar>
Something
</aside>
</section>
如此反复,我想找到任何解决方案,使内部从顶部div.post-entry
多远定位在像素值section#content
。
我遇到的主要问题是,我甚至看不到post-entry.offsetTop
的工作。这应该得到div.post-entry
相对于article.post
的偏移量,因为这是它的父亲。这实际上也适用于我。
var articleOffset = $('.post-entry').offsetTop;
console.log($('.post-entry')); //found and exists
console.log(articleOffset); undefined
任何想法为什么这不适合我吗?为什么我在这里的offsetTop
值未定义。有一个大的<h1>
,填充至少“30px”,抵消div.post-entry
。
关于这件事的任何想法? 也许任何其他很酷的解决方案如何做到这一点?我只想让aside#sidebar
的起始高度与div.post-entry
相同,但我不想更改标记。
好的,谢谢。这不会返回未定义的值,而是与$('。post-content')相同的值。offset()'... so'$('。post-content')[0] .offsetTop;'不知何故返回偏移量元素来自文档而不是来自父文档。我想知道'article#post'或者'section#content'中的'offsetTop'。 – matt 2012-07-24 19:31:44
明白了。我需要将'position:relative'设置为元素的包装。 – matt 2012-07-24 19:37:54