我正在使用bPaginate = false和sScrollY是某个固定高度的Jquery Datatables表。最终,我希望表在window.resize事件上调整大小。

为了使它起作用,我构建了一个较小的测试用例:在下面的代码段中,我希望在单击按钮时调整表的大小

HTML:

<!DOCTYPE html>
<html>
<head>
<link class="jsbin" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.13/jquery-ui.min.js"></script>
<script type="text/javascript" language="javascript" src="http://www.datatables.net/release-datatables/media/js/jquery.dataTables.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
  <input id="button" type="button" value="Click me!" />
  <table cellpadding="0" cellspacing="0" border="0" class="display" id="example">
    <thead>
        <tr>
            <th>Rendering engine</th>

            <th>Browser</th>
            <th>Platform(s)</th>
            <th>Engine version</th>
            <th>CSS grade</th>
        </tr>
    </thead>
    <tbody>
        <tr class="odd gradeX">
            <td>Trident</td>
            <td>Internet
                 Explorer 4.0</td>
            <td>Win 95+</td>
            <td class="center"> 4</td>
            <td class="center">X</td>

        </tr>
        <tr class="even gradeC">
            <td>Trident</td>
            <td>Internet
                 Explorer 5.0</td>
            <td>Win 95+</td>
            <td class="center">5</td>
            <td class="center">C</td>

        </tr>
        <tr class="odd gradeA">
            <td>Trident</td>
            <td>Internet
                 Explorer 5.5</td>
            <td>Win 95+</td>
            <td class="center">5.5</td>
            <td class="center">A</td>

        </tr>
    </tbody>
    <tfoot>
        <tr>
            <th>Rendering engine</th>
            <th>Browser</th>
            <th>Platform(s)</th>

            <th>Engine version</th>
            <th>CSS grade</th>
        </tr>
    </tfoot>
</table>
  </body>
</html>

Javascript:
$('#button').click(function() {
  console.log('Handler for .click() called.');
  table = $('#example').dataTable();
  settings = table.fnSettings();
  console.log('old:' + settings.oScroll.sY);
  settings.oScroll.sY = '150px';
  console.log('new:' + settings.oScroll.sY);
  table.fnDraw(false);
});
$('#example').dataTable({
  "sScrollY": "350px",
  "bPaginate": false,
  "bJQueryUI": true
});

控制台输出符合预期:
Handler for .click() called.
old:350px
new:150px

但是表格没有更新!知道我在做什么错吗?

可以在此处找到一个实时示例:http://jsbin.com/anegiw/12/edit

最佳答案

好吧,看起来不错的方法是利用datatbables框架添加的元素:

$(window).resize(function() {
  console.log($(window).height());
  $('.dataTables_scrollBody').css('height', ($(window).height() - 200));
});

$('#example').dataTable({
  "sScrollY": ($(window).height() - 200),
  "bPaginate": false,
  "bJQueryUI": true
});

本示例使表格可以随着窗口平滑地调整大小。

实时示例:http://jsbin.com/anegiw/18/edit

10-06 03:58