如何动态更改jQuery Datatables高度

我正在使用jQuery Datatables 。 我想在用户调整窗口大小时更改表的高度。 我能够捕捉窗口resize事件,它允许我计算新的高度。 如何为数据表对象分配新高度?

您可以使用以下代码:

var calcDataTableHeight = function() { return $(window).height() * 55 / 100; }; var oTable = $('#reqAllRequestsTable').dataTable({ "sScrollY": calcDataTableHeight(); }); $(window).resize(function() { var oSettings = oTable.fnSettings(); oSettings.oScroll.sY = calcDataTableHeight(); oTable.fnDraw(); }); 

目前的答案对我不起作用(使用v 1.9.1)。 我认为这个解决方案不仅有效,而且性能更好( 并且基于作者的建议 )。 此示例使用smartresize来解决跨浏览器窗口重新resize的问题。

 var defaultOptions = {...};//your options var calcDataTableHeight = function() { //TODO: could get crazy here and compute (parent)-(thead+tfoot) var h = Math.floor($(window).height()*55/100); return h + 'px'; }; defaultOptions.sScrollY = calcDataTableHeight(); var oTable = this.dataTable(defaultOptions); $(window).smartresize(function(){ $('div.dataTables_scrollBody').css('height',calcDataTableHeight()); oTable.fnAdjustColumnSizing(); }); 

简单地说就是这样:

 $('#example').dataTable({ "sScrollY": "auto" }); 

使用较新版本的Datatables,还有其他方法,当与明智地使用计时器一起观察resize事件触发器时,效果非常好。 对于那些卡住运行旧版DataTables的人来说,我已经离开了“古代”“window.location.reload()”行 – 只需取消注释并注释掉“table.draw()”调用。

旁注,文档说正确的调用是“table.Draw()” – 在我使用的版本中并非如此(调用全部为小写)。

 $(window).on('resize', function(e) { clearTimeout(resizeTimer); resizeTimer = setTimeout(function() { // Get table context (change "TABLENAME" as required) var table = $('#TABLENAME').DataTable(); // Set new size to height -100px $('.dataTables_scrollBody').css('height', window.innerHeight-100+"px"); // Force table redraw table.draw(); // Only necessary for ancient versions of DataTables - use INSTEAD of table.draw() // window.location.reload(); }, 250); // Timer value for checking resize event start/stop }); 

而已。

对于DataTables 1.10

  $("#table").DataTable( { scrollY: '250px', scrollCollapse: true, paging: false, }); $('#table').closest('.dataTables_scrollBody').css('max-height', '500px'); $('#table').DataTable().draw(); 

更改CSS时,必须调用draw()

这对我有用

 $(document).ready(function () { $('#dataTable1').dataTable({ "scrollY": 150, "scrollX": 150 }); $('.dataTables_scrollBody').height('650px'); }); 

这是一个简单的解决方案,如此处所述

  $(document).ready(function() { $('#example').DataTable( { scrollY: '50vh', scrollCollapse: true, paging: false }); }); 

vh相对于视口高度的1%*

您可以使用vh单位设置根据窗口大小而变化的高度。

支持:Chrome 20.0 +,IE 9.0 +,FireFox 19.0 +,Safari 6.0 +,Opera 20.0+

我想你可以用css改变表的高度

 $(window).resize(function(){ $('#yourtable').css('height', '100px'); });