jquery - 为什么 $(...).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,我怎样才能得到元素的实际位置?
谢谢!
解决方案
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>
推荐阅读
- python - 将多个视图引用到一个模板 django 的子类列表视图
- html - 为什么我的页面宽度不适合所有分辨率
- gnuplot - 如何使用 gnuplot 制作更小的 eps 文件?
- typescript - 为什么 localStorage 不能使用打字稿?
- functional-programming - 递归和尾调用优化示例
- python - 使用 Cloud Functions 和 Cloud Scheduler 创建到 BigQuery 的数据管道
- css - 是否可以仅在带有 CSS 的网格上将背景图像放在 amChart XY 图表中?
- machine-learning - 知道我有 9 个属性,我如何可视化我的数据集?
- android - 如何正确使用自定义视图位图?
- python - 创建图像缩略图失败并出现 TypeError: 'int' object is not subscriptable