简体   繁体   中英

How to detect exact offset top() using jquery after scroll?

I have a table i want to detect offset top of TR where is clicked this is working fine but after scroll page this is not working fine. Why after scroll offset().top is changed? How can fix it?

 $(function() { $('tr').click(function() { offsetTop = $(this).offset().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"> <table class="table table-bordered"> <thead> <tr> <th>Firstname</th> <th>Lastname</th> <th>Email</th> </tr> </thead> <tbody> <tr> <td>John</td> <td>Doe</td> <td>john@example.com</td> </tr> <tr> <td>Mary</td> <td>Moe</td> <td>mary@example.com</td> </tr> <tr> <td>July</td> <td>Dooley</td> <td>july@example.com</td> </tr> <tr> <td>July 1</td> <td>Dooley</td> <td>july@example.com</td> </tr> <tr> <td>July 2</td> <td>Dooley</td> <td>july@example.com</td> </tr> <tr> <td>July 3</td> <td>Dooley</td> <td>july@example.com</td> </tr> <tr> <td>July 4</td> <td>Dooley</td> <td>july@example.com</td> </tr> <tr> <td>July 5</td> <td>Dooley</td> <td>july@example.com</td> </tr> <tr> <td>July 6</td> <td>Dooley</td> <td>july@example.com</td> </tr> <tr> <td>July 7</td> <td>Dooley</td> <td>july@example.com</td> </tr> <tr> <td>July 8</td> <td>Dooley</td> <td>july@example.com</td> </tr> <tr> <td>July 9</td> <td>Dooley</td> <td>july@example.com</td> </tr> <tr> <td>July 10</td> <td>Dooley</td> <td>july@example.com</td> </tr> </tbody> </table> </div>

You could always calculate the offset, factoring in the scroll position:

var offset_t = $(selector).offset().top - $(window).scrollTop();
var offset_l = $(selector).offset().left - $(window).scrollLeft();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM