首页 > 解决方案 > 为什么 $(...).position().top 返回 0?

问题描述

假设我有以下代码:

<div style="height: 50px; width: 50px; background: black"></div>

<table id="pets" class="table-border" style="width: 800px; margin-top: 1em; border-collapse: collapse">
    <tr>
        <td>Name</td>
        <td>Breed</td>
        <td class="highlightTop">Age</td>
    </tr>
    <tr>
        <td><input type="text" name="petName" style="width: 100%"/></td>
        <td>...</td>
        <td class="highlight"><input type="numbers" name="age" style="width: 100%"/></td>
</table>

当我这样做时,$('#pets .highlightTop').position().top我得到 0 回来。为什么?桌子上方有一个 50px 高的 div 的事实应该意味着它至少是 50,不是吗?

既然不是 50,我怎样才能得到元素的实际位置?

谢谢!

https://jsfiddle.net/c1qj09sn/

标签: jquery

解决方案


position返回元素相对于其父元素的位置。

所以相对于#pets。哪个是 0

你正在寻找的是offset

在这种情况下,偏移量的值将是

50(您的元素和文档 div 顶部之间唯一元素的高度)+ 16px(=1em margin-top of parent)+ 8px(body margin)=72px

console.log($('#pets .highlightTop').offset().top);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="height: 50px; width: 50px; background: black"></div>

<table id="pets" class="table-border" style="width: 800px; margin-top: 1em; border-collapse: collapse">
    <tr>
        <td>Name</td>
        <td>Breed</td>
        <td class="highlightTop">Age</td>
    </tr>
    <tr>
        <td><input type="text" name="petName" style="width: 100%"/></td>
        <td>...</td>
        <td class="highlight"><input type="numbers" name="age" style="width: 100%"/></td>
</table>

在这里阅读更多-> jquery-difference-between-position-and-offset


推荐阅读