javascript - 为什么 position().top 在第二个表中返回错误的值?
问题描述
我在第一个表中有两个表,它的返回 position().top 很好,但是当我点击第二个表时,它返回与第一个表相同的值,我该如何修复它?
为什么两个表 position().top 返回相同?
$(function() {
$('tr').click(function() {
offsetTop = $(this).position().top;
console.log(offsetTop);
});
});
.myDiv {
overflow-y: auto;
height: 250px;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<div class="myDiv">
<h2>Table 1</h2>
<table class="table table-bordered">
<tbody>
<tr>
<td>Click here this is first table, its return -1 in console</td>
</tr>
</tbody>
</table>
<h2>Table 2</h2>
<table class="table table-bordered">
<tbody>
<tr>
<td>Click here this is second table, its also return -1 in console why? how can i fix it? how can i get exactly position of this element?</td>
</tr>
</tbody>
</table>
</div>
解决方案
我假设您试图获得top
相对于screen top
,而不是相对于它的父级。
在这种情况下,您应该使用offset()
和子结构window.scrollY
$(function() {
$('tr').click(function() {
offsetTop = $(this).offset().top - window.scrollY;
console.log(offsetTop);
});
});
.myDiv {
overflow-y: auto;
height: 250px;
}
#d {
height: 300px;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<div id="d"></div>
<div class="myDiv">
<h2>Table 1</h2>
<table class="table table-bordered">
<tbody>
<tr id="2">
<td>Click and see how its top changed with scroll</td>
</tr>
</tbody>
</table>
<h2>Table 2</h2>
<table class="table table-bordered">
<tbody>
<tr>
<td>See how its top changed with scroll</td>
</tr>
</tbody>
</table>
</div>
推荐阅读
- python - 转换为日期时间 Python 时的错误处理
- mysql-workbench - 添加列时如何将 SRID 4326(空间类型)添加到 Workbench?
- python - RandomWalker 分割算法的分割结果与初始种子相同
- arrays - Error NgFor 仅支持绑定到 Iterables,例如 Arrays。如何将 JSON 对象转换为数组对象?
- javascript - IFormContext 只引用了一个类型,但在这里用作值
- android - 当我可以使用静态函数时,为什么还要使用 Dagger 或 Hilt DI?
- javascript - 我可以在没有 npm 或 node.js 的情况下使用 .dotenv 库作为 HTML 脚本导入吗?
- ios - 防止 SwiftUI 动画覆盖嵌套的 withAnimation 块
- python - 如何根据数据框的行值作为子字符串/包含在另一个数据框的行值中来连接两个数据框?
- python - 删除所有子域并仅获取根域 pyspark