当我们调整窗口大小时,如何使用jquery为数据表元素指定高度

Raj*_*aje 4 jquery datatables

我正在使用jquery数据表来显示数据.在body上使用以下代码设置其高度

<table id="RequestsTable" cellpadding="0" cellspacing="0" border="0" class="display" style="width:100%;">
Run Code Online (Sandbox Code Playgroud)

在脚本中,我写下了以下代码.ScrollY根据窗口高度计算高度,并在表单加载时分配给数据表.

<script type="text/javascript">
var scrollY = $(window).height()*58/100;

var oTable = $('#RequestsTable').dataTable({
    "sScrollY": scrollY,
    "bPaginate": true,
    "bScrollCollapse": true,

    } );
Run Code Online (Sandbox Code Playgroud)

当窗口调整大小并分配给数据表时,我想再次计算高度.我试过以下代码,但没有为我工作.

var scrollY = $(window).height()*58/100;    
$(window).resize(function () {  
scrollY = $(window).height()*58/100;
});

    var oTable = $('#RequestsTable').dataTable({
        "sScrollY": scrollY,
        "bPaginate": true,
        "bScrollCollapse": true,

        } );
Run Code Online (Sandbox Code Playgroud)

任何人都有任何想法可以实现这一点.提前致谢.

我试过这个,但没有运气

function calcDataTableHeight () {
    return $(window).height()*58/100;
};

$(window).resize(function () {

   var oSettings = oTable.fnSettings();
    oSettings.sScrollY = calcDataTableHeight();
    oTable.fnDraw();
});

var oTable = $('#reqAllRequestsTable').dataTable({
    "sScrollY": calcDataTableHeight()});
Run Code Online (Sandbox Code Playgroud)

任何其他方式都可以使用CSS设置高度?

Nik*_*iko 7

更新变量是不够的,您需要将新高度传递给datatable插件(因为当变量的内容更改时它不会自动更新):

var $window = $(window);

var calcDataTableHeight = function() {
    return Math.round($window.height() * 0.58);
};

var oTable = $('#RequestsTable').dataTable({
    "sScrollY": calcDataTableHeight(),
    "bPaginate": true,
    "bScrollCollapse": true,
});

$window.resize(function() {
    var oSettings = oTable.fnSettings();
    oSettings.oScroll.sY = calcDataTableHeight(); // <- updated!

    // maybe you need to redraw the table (not sure about this)
    oTable.fnDraw(false);
});
Run Code Online (Sandbox Code Playgroud)