How to dynamically change jQuery Datatables height

前端 未结 8 1878
情话喂你
情话喂你 2021-01-31 05:25

I\'m using jQuery Datatables. I want to change the height of the table whenever a user resizes the window. I\'m able to catch the window resize event which allows me to calculat

相关标签:
8条回答
  • 2021-01-31 05:38

    You can use the following code:

    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();
    });
    
    0 讨论(0)
  • 2021-01-31 05:39

    Simply put it like this:

    $('#example').dataTable({
       "sScrollY": "auto"
    });
    
    0 讨论(0)
  • 2021-01-31 05:43

    For DataTables 1.10:

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

    When you changed CSS you must call draw().

    0 讨论(0)
  • 2021-01-31 05:48

    I think you can change the height of the table by css

    $(window).resize(function(){
           $('#yourtable').css('height', '100px');
    });
    
    0 讨论(0)
  • 2021-01-31 05:52

    This is work for me

    $(document).ready(function () {
                $('#dataTable1').dataTable({
                    "scrollY": 150,
                    "scrollX": 150
                });
                $('.dataTables_scrollBody').height('650px');
            });
    
    0 讨论(0)
  • 2021-01-31 05:53

    The current answer didn't work for me (using v 1.9.1). I think this solution not only works but will perform better (and is based on the author's suggestion). This example is using smartresize to solve cross browser window re-size issues.

    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();
    });
    
    0 讨论(0)
提交回复
热议问题