[英]Why position().top return wrong value in second table?
我在第一個表中有兩個表,它的返回位置()。頂部很好,但是當我單擊第二個表然后它返回與第一個表中相同的值時,我該如何修復它?
為什么兩個表 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>
您可以使用tr
position
獲取table
position
和總和,實際上, position()
返回元素位置取決於自己的父位置。
$(function() { $('tr').click(function() { offsetTop = $(this).position().top; offsetTopParent = $(this).parents('table').position().top; //console.log(offsetTop); // return tr offset //console.log(offsetTopParent); // return table offset console.log(offsetTop + offsetTopParent); }); });
.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> <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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.