[removed] Scroll to nth row in a table?

前端 未结 5 891
暖寄归人
暖寄归人 2020-12-30 05:21

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

相关标签:
5条回答
  • 2020-12-30 06:05

    Latest update (no-jquery for for modern browsers)

    var rows = document.querySelectorAll('#tableid tr');
    
    // line is zero-based
    // line is the row number that you want to see into view after scroll    
    rows[line].scrollIntoView({
        behavior: 'smooth',
        block: 'center'
    });
    

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


    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/

    0 讨论(0)
  • 2020-12-30 06:05

    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.

    0 讨论(0)
  • 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);
    }
    
    0 讨论(0)
  • 2020-12-30 06:19

    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);
        };
    });
    
    0 讨论(0)
  • 2020-12-30 06:22

    Don't use jQuery - it slows down sites!

    var elem = document.getElementById("elem_id");  
    elem.scrollIntoView(true); 
    
    0 讨论(0)
提交回复
热议问题