javascript - JS 中相对于parent.parent 容器的位置元素?没有绝对/固定定位?

标签 javascript jquery zepto

我遇到了一个棘手的问题,我正在拼命寻找可行的解决方案。

一个article#post和一个 aside#sidebar并排 float - 相当简单。 在我的里面article#posth1和一个 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/

相关文章:

javascript - 如何在一个页面上运行多个版本的 Zepto.js?

animation - 如何停止 Zepto 动画?

javascript - 尝试使用 jQuery 执行 AJAX 不起作用

jquery - Angular 数仅输入限制 0

jquery - 与 Laravel Mix 一起使用时 TinyMCE 主题文件丢失

jquery - 如何使用 $.ajax(jQuery 或 Zepto)发布对象数组

javascript - 在具有多个 $http.get 的服务中使用带有闭包的 Promise

javascript - 如何从xhr获取标题?

javascript - 按首字母 Javascript 的字母顺序对对象进行排序和分组

javascript - 反向 for 循环的 lodash 等价物是什么?