Как установить ширину столбца в JQuery Datatable? - PullRequest
33 голосов
/ 08 апреля 2011

У меня есть таблица данных jQuery (выделена красным), но происходит то, что таблица выпрыгивает из ширины, которую я установил для div (которая равна 650 px).

Вот снимок экрана: enter image description here

Вот мой код:

<script type="text/javascript">

    var ratesandcharges1;

    $(document).ready(function() {

        /* Init the table*/
        $("#ratesandcharges1").dataTable({
            "bRetrieve": false,
            "bFilter": false,
            "bSortClasses": false,
            "bLengthChange": false,
            "bPaginate": false,
            "bInfo": false,
            "bJQueryUI": true,
            "bAutoWidth": false,
            "aaSorting": [[2, "desc"]],
            "aoColumns": [
            { sWidth: '9%' },
            { sWidth: '9%' },
            { sWidth: '9%' },
            { sWidth: '9%' },
            { sWidth: '9%' },
            { sWidth: '9%' },
            { sWidth: '9%' },
            { sWidth: '9%' },
            { sWidth: '9%' },
            { sWidth: '9%' },
            { sWidth: '10%' } ]
        });

        ratesandcharges1.fnDraw();

    });
</script>
<div id="ratesandcharges1Div" style="width: 650px;"> 


<table id="ratesandcharges1" class="grid" >
    <thead>
        <!--Header row-->
        <tr>
            <th>Charge Code</th>
            <th>Rates</th>
            <th>Quantity</th>
            <th>Total Charge</th>
            <th>VAT %</th>
            <th>Calc. Type</th>
            <th>Paid By</th>
            <th>From</th>
            <th>To</th>
            <th>VAT</th>
            <th>MVGB</th>
         </tr>
    </thead>
    <!--Data row-->
    <tbody>
        <tr>
            <td>Day/Tag</td>
            <td>55.00</td>
            <td>3.00</td>
            <td>165.00</td>
            <td>20.00</td>
            <td>Rental Time</td>
            <td>Bill-to/Agent</td>
            <td>5/11/2010</td>
            <td>08/11/2010</td>
            <td>33.00</td>
            <td>1.98</td>
        </tr>
        <tr>
            <td>PAI</td>
            <td>7.50</td>
            <td>3.00</td>
            <td>22.50</td>
            <td>20.00</td>
            <td>Rental Time</td>
            <td>Driver/Cust.</td>
            <td>5/11/2010</td>
            <td>08/11/2010</td>
            <td>4.50</td>
            <td>0.00</td>
        </tr>
        <tr>
            <td>BCDW</td>
            <td>15.00</td>
            <td>3.00</td>
            <td>45.00</td>
            <td>20.00</td>
            <td>Rental Time</td>
            <td>Driver/Cust.</td>
            <td>5/11/2010</td>
            <td>08/11/2010</td>
            <td>9.00</td>
            <td>0.54</td>
        </tr>
        <tr>
            <td>BTP</td>
            <td>7.15</td>
            <td>3.00</td>
            <td>21.45</td>
            <td>20.00</td>
            <td>Rental Time</td>
            <td>Driver/Cust.</td>
            <td>5/11/2010</td>
            <td>08/11/2010</td>
            <td>4.29</td>
            <td>0.26</td>
        </tr>
    </tbody>
</table>
</div>    

Есть идеи?

Спасибо

Ответы [ 7 ]

34 голосов
/ 28 июня 2012

Я нашел это на 456 Bera St. Man, это спасатель !!!

http://www.456bereastreet.com/archive/200704/how_to_prevent_html_tables_from_becoming_too_wide/

Но - у вас мало места для ваших данных.

CSS FTW:

<style>
table {
    table-layout:fixed;
}
td{
    overflow:hidden;
    text-overflow: ellipsis;
}
</style>
23 голосов
/ 15 декабря 2012

Параметры конфигурации:

$(document).ready(function () {

  $("#companiesTable").dataTable({
    "sPaginationType": "full_numbers",
    "bJQueryUI": true,
    "bAutoWidth": false, // Disable the auto width calculation 
    "aoColumns": [
      { "sWidth": "30%" }, // 1st column width 
      { "sWidth": "30%" }, // 2nd column width 
      { "sWidth": "40%" } // 3rd column width and so on 
    ]
  });
});

Укажите css для таблицы:

table.display {
  margin: 0 auto;
  width: 100%;
  clear: both;
  border-collapse: collapse;
  table-layout: fixed;         // add this 
  word-wrap:break-word;        // add this 
}

HTML:

<table id="companiesTable" class="display"> 
  <thead>
    <tr>
      <th>Company name</th>
      <th>Address</th>
      <th>Town</th>
    </tr>
  </thead>
  <tbody>

    <% for(Company c: DataRepository.GetCompanies()){ %>
      <tr>  
        <td><%=c.getName()%></td>
        <td><%=c.getAddress()%></td>
        <td><%=c.getTown()%></td>
      </tr>
    <% } %>

  </tbody>
</table>

У меня работает!

13 голосов
/ 08 апреля 2011

Попробуйте установить ширину на самом столе:

<table id="ratesandcharges1" class="grid" style="width: 650px;">

Вам придется настроить 650 на пару пикселей, чтобы учесть любые отступы, поля и границы.

Возможно, у вас все еще будут проблемы. Я не вижу достаточного горизонтального пространства для всех этих столбцов без искажения заголовков, уменьшения размеров шрифта или какого-либо другого уродства.

3 голосов
/ 25 января 2016

Ответ с официального сайта

https://datatables.net/reference/option/columns.width

$('#example').dataTable({
    "columnDefs": [
        {
            "width": "20%",
            "targets": 0
        }
    ]
});
3 голосов
/ 15 июля 2014

Лучшее решение, которое я нашел, сработало для меня, ребята, после того, как попробовал все остальные решения .... В основном я установил sScrollX на 200%, а затем установил ширину отдельных столбцов на требуемый%, который я хотел. Чем больше столбцов у вас есть, и чем больше места вам нужно, тем больше нужно поднять sScrollX% ... Нулевое значение означает, что я хочу, чтобы эти столбцы сохранили автоматическую ширину таблицы данных, которую они установили в своем коде. enter image description here

            $('#datatables').dataTable
            ({  
                "sScrollX": "200%", //This is what made my columns increase in size.
                "bScrollCollapse": true,
                "sScrollY": "320px",

                "bAutoWidth": false,
                "aoColumns": [
                    { "sWidth": "10%" }, // 1st column width 
                    { "sWidth": "null" }, // 2nd column width 
                    { "sWidth": "null" }, // 3rd column width
                    { "sWidth": "null" }, // 4th column width 
                    { "sWidth": "40%" }, // 5th column width 
                    { "sWidth": "null" }, // 6th column width
                    { "sWidth": "null" }, // 7th column width 
                    { "sWidth": "10%" }, // 8th column width 
                    { "sWidth": "10%" }, // 9th column width
                    { "sWidth": "40%" }, // 10th column width
                    { "sWidth": "null" } // 11th column width
                    ],
                "bPaginate": true,              
                "sDom": '<"H"TCfr>t<"F"ip>',
                "oTableTools": 
                {
                    "aButtons": [ "copy", "csv", "print", "xls", "pdf" ],
                    "sSwfPath": "copy_cvs_xls_pdf.swf"
                },
                "sPaginationType":"full_numbers",
                "aaSorting":[[0, "desc"]],
                "bJQueryUI":true    

            });
2 голосов
/ 03 октября 2011

В java-скрипте вычислите ширину, используя следующий код

var scrollX = $(window).width()*58/100;
var oTable = $('#reqAllRequestsTable').dataTable({
    "sScrollX": scrollX
    } );
0 голосов
/ 27 февраля 2019

с помощью css мы можем легко добавить ширину к столбцу.

здесь я добавляю ширину первого столбца к 300px в заголовке (thead)

::ng-deep  table thead tr:last-child th:nth-child(1) {
    width: 300px!important;
}

теперь добавьте ту же ширину к первому столбцу tbody,

  <table datatable class="display table ">
            <thead>
            <tr>
                <th class="text-left" style="width: 300px!important;">name</th>
            </tr>
            </thead>
            <tbody>
           
            <tr>
                <td class="text-left" style="width: 300px!important;">jhon mathew</td>
                
            </tr>
            </tbody>
        </table>
       

тем самым вы можете легко изменить ширину, изменив порядок n-го дочернего элемента. если вам нужно 3 столбца, добавьте nth-child (3)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...