1

我正在使用nicescroll 插件处理一个简单的表。

在加载表格时自动滚动到底部,我还添加了一个按钮,该按钮添加了一个新行并滚动到底部。

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

希望你能帮助我。

谢谢

这是我的示例代码

// 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('');
});
4

2 回答 2

3

只需更改一点您的 js 代码

方式一

...
// 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);
  });
});
...

方式二

...
// 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);      
  }
});
于 2018-06-29T08:02:58.783 回答
1

找到了答案。

setTimeout(function(){ 
  $('tbody').animate({
  scrollTop: $('tbody').get(0).scrollHeight}, 2000);
}, 500);
于 2018-06-29T08:19:32.857 回答