自动滚动到最后一行 table

Auto scroll to last row of table

我正在使用 nicescroll plugin 开发一个简单的 table。

加载 table 自动滚动到底部时,我还添加了一个按钮,它添加了一个新行并滚动到底部。

我的问题是,当我添加一个新的输入字段以根据用户输入生成行时,它不会滚动到最后一行,有时会在中间跳动。

希望你能帮助我。

谢谢

这是我的 sample code

// add scroll

$('tbody').niceScroll({autohidemode: false});

// add 1 row
$('button').click(function(){

        var rowCount = $('table > tbody tr').length + 1;

    $('tbody').append('<tr><td>item'+ rowCount +'</td><td>items</td><td>items</td><td>items</td><td>items</td></tr>');

  $('tbody').animate({
  scrollTop: $('tbody').get(0).scrollHeight}, 2000);

});

// scroll to bottom on load
$('tbody').animate({
  scrollTop: $('tbody').get(0).scrollHeight}, 2000);

// generate rows
$('input').keyup(function(){
  $('table tbody tr').remove();
  $('tbody').animate({
  scrollTop: $('tbody').get(0).scrollHeight}, 2000);

  var rowCount = $('table > tbody tr').length + 1;  
    for(var i = 1; i <= $(this).val(); i++ ){
     $('tbody').append('<tr><td>item'+ i +'</td><td>items</td><td>items</td><td>items</td><td>items</td></tr>'); 
    }

});

// clear value on input field
$('input').click(function(){
    $(this).val('');
});

只改变一点你的js代码

Way 1

...
// generate rows
$('input').keyup(function(){
  // Clean table
  $('table tbody tr').remove();
  // Add new rows
  var rowCount = $('table > tbody tr').length + 1;  
  for(var i = 1; i <= $(this).val(); i++ ){
     $('tbody').append('<tr><td>item'+ i +'</td><td>items</td><td>items</td><td>items</td><td>items</td></tr>'); 
  }
  // Then stop previous anim with clean anim queue (added by every key typed in input) and finally add new anim
  $('tbody').stop(true, false).animate({
      scrollTop: $('tbody').get(0).scrollHeight}, 2000);
  });
});
...

Way 2

...
// generate rows
$('input').keyup(function(){
  $('table tbody tr').remove();  
  var rowCount = $('table > tbody tr').length + 1;  
  for(var i = 1; i <= $(this).val(); i++ ){
    $('tbody').append('<tr><td>item'+ i +'</td><td>items</td><td>items</td><td>items</td><td>items</td></tr>'); 
    // Animate during row adding  
    $('tbody').stop().animate({scrollTop: $('tbody').get(0).scrollHeight}, 2000);      
  }
});

找到答案。

setTimeout(function(){ 
  $('tbody').animate({
  scrollTop: $('tbody').get(0).scrollHeight}, 2000);
}, 500);