[removed] Scroll to nth row in a table?

2019-02-06 09:55发布

Using either pure Javascript or jQuery, how do I scroll the page so that the nth row in a table is centered on the page?

Some examples I've seen that have this sort of feature usually require that the element I scroll to uses an id as the selector, but since the table has a dynamic amount of rows and may be paged, I'd rather not go this route of having to give each <td> tag an id.

Is the easiest way to just calculate the position of the td relative to the top of the document and scroll the window using setInterval until the middle of the window is >= to the position of the nth <td> tag?

I suppose some pseudo-code of the way I imagine it working would be:

function scrollToNthTD(i) {
  var position = CalculatePositionOfTR(i);
  var timer = setTimeout(function () {
    ScrollDownALittle();
    if( CenterOfVerticalWindowPosition > position)
      clearInterval(timer);
  }, 100);
}

5条回答
forever°为你锁心
2楼-- · 2019-02-06 10:22

Give this a shot:

/*pseudo-code*/
$("td.class").bind("click", function() {

    var y = $(this).position().top,
        h = $(window).height();

    if(y > h/2) {
        $("body").animate({
            scrollTop: y - h/2
        }, 2000);
    };
});
查看更多
狗以群分
3楼-- · 2019-02-06 10:27

Since you can use jQuery here it is..

var w = $(window);
var row = $('#tableid').find('tr').eq( line );

if (row.length){
    w.scrollTop( row.offset().top - (w.height()/2) );
}

Demo at http://jsfiddle.net/SZKJh/


If you want it to animate instead of just going there use

var w = $(window);
var row = $('#tableid').find('tr').eq( line );

if (row.length){
    $('html,body').animate({scrollTop: row.offset().top - (w.height()/2)}, 1000 );
}

Demo at http://jsfiddle.net/SZKJh/1/

查看更多
家丑人穷心不美
4楼-- · 2019-02-06 10:34

You can do something like this

function CalculatePositionOfTR(){
    return $('tr:eq(' + i + ')').offset().top;
}

function ScrollDownALittle(position){
    $('html, body').animate({
         scrollTop: position
     }, 2000);
}


function scrollToNthTD(i) {
  var position = CalculatePositionOfTD(i);
  var timer = setTimeout(function () {
    ScrollDownALittle(position);
    if( CenterOfVerticalWindowPosition > position)
      clearInterval(timer);
  }, 100);
}
查看更多
我命由我不由天
5楼-- · 2019-02-06 10:35

aka-g-petrioli

I have corrected the followings from your answer.

 $('#control button').click(function(){
    var w = $(window);
    var row = table.find('tr')
        .removeClass('active')
        .eq( +$('#line').val() )
        .addClass('active');

    if (row.length){
        w.scrollTop( row.offset().top - row.offset().top/5);
    }
});

This will help you to scroll accurate position.

查看更多
在下西门庆
6楼-- · 2019-02-06 10:39

Don't use jQuery - it slows down sites!

var elem = document.getElementById("elem_id");  
elem.scrollIntoView(true); 
查看更多
登录 后发表回答