当添加一行时,数据表滚动到底部

jQuery Datatables scroll to bottom when a row is added

本文关键字:数据表 滚动 底部 一行 添加      更新时间:2023-09-26

我希望我的DataTable在添加一行时滚动到底部。我已经尝试了多个修复这个问题,但没有一个工作。

测试解决方案:

  • 如何在数据表中加载表,并在加载时自动滚动到最后记录
  • Jquery DataTable auto scroll to bottom on load

等等……

我认为我的案例与其他案例的区别在于,我使用的是DataTable, D大写。

总之,这是我当前的代码:

var table = $('#example').DataTable({
          "createdRow": function( row, data, dataIndex ) 
          {
             $(row).attr('id', 'row-' + dataIndex);
          },
          "bPaginate": false,
        "bLengthChange": false,
        "bFilter": false,
        "bInfo": false,
        "bAutoWidth": false,
        "scrollY":        $(window).height()/1.5,
        "scrollCollapse": true,
        "paging":         false,
   });
   for(var i = 1; i <= 20; i++){
      table.row.add([ 
         i,
         'action'+i,
      ]);
   }  
   table.draw();
   table.rowReordering();

每当添加新行时,如果表滚动到底部就好了。

SOLUTION

要滚动到表格底部,使用下面的代码:

var $scrollBody = $(table.table().node()).parent();
$scrollBody.scrollTop($scrollBody.get(0).scrollHeight);

演示

$(document).ready( function () {
   var table = $('#example').DataTable({
      "createdRow": function( row, data, dataIndex ) {
         $(row).attr('id', 'row-' + dataIndex);
        console.log($(row).closest('table').parent());
      },
      "scrollY":        $(window).height()/1.5,
      "scrollCollapse": true,
      "paging": false
   });
   $('#btn-add').click(function(){    
      for(var i = 1; i <= 10; i++){
         table.row.add([ 
            i,
            i + '.2',
            i + '.3',
            i + '.4',
            i + '.5',
            i + '.6'
         ]);
      }  
   
      table.draw();      
      // Scroll to the bottom
      var $scrollBody = $(table.table().node()).parent();
      $scrollBody.scrollTop($scrollBody.get(0).scrollHeight);
   });
  
   table.rowReordering();
} );
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>jQuery DataTables</title>  
<link href="//cdn.datatables.net/1.10.7/css/jquery.dataTables.min.css" rel="stylesheet" type="text/css" />
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="http://cdn.datatables.net/1.10.7/js/jquery.dataTables.min.js"></script>
<script src="https://code.jquery.com/ui/1.9.2/jquery-ui.min.js"></script>
<script src="https://cdn.rawgit.com/mpryvkin/jquery-datatables-row-reordering/95b44786cb41cf37bd3ad39e39e1d216277bd727/media/js/jquery.dataTables.rowReordering.js"></script>
</head>
  
<body>
  
<button id="btn-add" type="button">Add records</button>
  
<table id="example" class="display" width="100%">
<thead>
<tr>
  <th>Name</th>
  <th>Position</th>
  <th>Office</th>
  <th>Age</th>
  <th>Start date</th>
  <th>Salary</th>
</tr>
</thead>
<tfoot>
<tr>
  <th>Name</th>
  <th>Position</th>
  <th>Office</th>
  <th>Age</th>
  <th>Start date</th>
  <th>Salary</th>
</tr>
</tfoot>
<tbody>
</tbody>
</table>
</body>
</html>