我遇到了一个棘手的问题,我正在拼命寻找可行的解决方案。
一个article#post
和一个 aside#sidebar
并排 float - 相当简单。
在我的里面article#post
是 h1
和一个 div.post-entry
.
我想知道是否可以以某种方式确定 div.post-entry
的相对偏移量到外容器section#content
。我想这样做的原因是这样我可以用 margin-top
定位 float 侧边栏。与“div.post-entry”高度相同。
这是我当前 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
相同的高度开始但我不想更改标记。
最佳答案
您需要从 jQuery 对象中选择 DOM 元素。
var articleOffset = $('.post-content')[0].offsetTop;
关于javascript - JS 中相对于parent.parent 容器的位置元素?没有绝对/固定定位?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11637866/