首页 > 解决方案 > 为什么 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>

标签: javascriptjquery

解决方案


我假设您试图获得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>


推荐阅读