【问题标题】:positon element relative to parent.parent container in JS? no absolute/fixed positioning?JS中相对于parent.parent容器的位置元素?没有绝对/固定定位?
【发布时间】:2012-07-23 04:25:24
【问题描述】:

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

article#postaside#sidebar 并排浮动 - 相当简单。 在我的article#post 里面是一个h1 和一个div.post-entry

我想知道我是否可以以某种方式确定div.post-entry 与外部容器section#content 的相对偏移量。我想这样做的原因是我可以将带有margin-top 的浮动侧边栏定位在与“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 值未定义。有一个很大的&lt;h1&gt;,其填充至少为“30px”,可以抵消div.post-entry

关于这件事有什么想法吗? 也许还有其他关于如何做到这一点的酷解决方案?我只想让aside#sidebar 从与div.post-entry 相同的高度开始,但我不想更改标记。

【问题讨论】:

    标签: javascript jquery zepto


    【解决方案1】:

    您需要从 jQuery 对象中选择 DOM 元素。

    var articleOffset = $('.post-content')[0].offsetTop;
    

    【讨论】:

    • 好的,谢谢。这不会返回未定义但与$('.post-content').offset() 相同的值......所以$('.post-content')[0].offsetTop; 以某种方式返回元素与文档而不是其父元素的偏移量。我想从article#post 甚至section#content 中了解offsetTop
    • 知道了。我需要将position:relative 设置为元素的包装器。
    猜你喜欢
    • 2020-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-21
    • 2013-06-16
    • 1970-01-01
    • 2011-10-11
    • 2021-01-17
    相关资源
    最近更新 更多