Datatables - установка ширины столбца
Я пытаюсь настроить ширину столбцов, как показано ниже:
var per_page = $("table").data("per_page");
$(".table").dataTable({
"aoColumnDefs": [
{ "sWidth": "100px", "aTargets": [ 1 ] },
{ "sWidth": "100px", "aTargets": [ 2 ] },
{ "sWidth": "100px", "aTargets": [ 3 ] },
{ "sWidth": "100px", "aTargets": [ 4 ] },
{ "sWidth": "100px", "aTargets": [ 5 ] },
{ "sWidth": "100px", "aTargets": [ 6 ] },
{ "sWidth": "100px", "aTargets": [ 7 ] }
],
"aoColumns" : [
{ "sWidth": "100px"},
{ "sWidth": "100px"},
{ "sWidth": "100px"},
{ "sWidth": "100px"},
{ "sWidth": "100px"},
{ "sWidth": "100px"},
{ "sWidth": "100px"},
{ "sWidth": "100px"},
],
bJQueryUI: true,
iDisplayLength: per_page,
"fnDrawCallback": function( oSettings ) {
if (oSettings._iDisplayLength == per_page)
return true
else {
$.post($(this).data("url"), {iDisplayLength: oSettings._iDisplayLength})
.done(function(data){
if (data.success)
per_page = oSettings._iDisplayLength;
});
}
}
})
Но результирующая ширина столбца не то, что я пытаюсь установить. не могли бы вы мне помочь?
Обновление 1
Я обновил код инициализации следующим образом, но столкнулся с странным поведением в IE 9:
Т.е. он занимает самое длинное поле, делит его на строки и берет его по умолчанию для всех строк этого столбца.
var per_page = $("table").data("per_page");
$(".table").dataTable({
sScrollX: "100%",
aoColumns : [
{ "sWidth": "15%"},
{ "sWidth": "15%"},
{ "sWidth": "15%"},
{ "sWidth": "15%"},
{ "sWidth": "15%"},
{ "sWidth": "15%"},
{ "sWidth": "15%"},
],
bJQueryUI: true,
iDisplayLength: per_page,
"fnDrawCallback": function( oSettings ) {
if (oSettings._iDisplayLength == per_page)
return true
else {
$.post($(this).data("url"), {iDisplayLength: oSettings._iDisplayLength})
.done(function(data){
if (data.success)
per_page = oSettings._iDisplayLength;
});
}
}
})
Обновление 2
Я обновил код, как показано ниже, результат в том, что 9 - это то, что заголовок datatable изменен до нового размера, но остальная часть таблицы не затронута изменениями, см. Снимок экрана http://gyazo.com/282967b051366b18634d4e778205c938
код инициализации:
var per_page = $("table").data("per_page");
var datTable = $(".table").dataTable({
sScrollX: "100%",
sScrollX: "500px",
aoColumnDefs: [
{ bSortable: false, aTargets: [ 4, 5,6 ] },
{ sWidth: "16%", aTargets: [ 1, 2,3,4,5,6 ] },
],
bJQueryUI: true,
sAutoWidth: false,
iDisplayLength: per_page,
"fnDrawCallback": function( oSettings ) {
if (oSettings._iDisplayLength == per_page)
return true
else {
$.post($(this).data("url"), {iDisplayLength: oSettings._iDisplayLength})
.done(function(data){
if (data.success)
per_page = oSettings._iDisplayLength;
});
}
}
})
Как я могу исправить это поведение?
Ответы
Ответ 1
Я вижу в вашем обновлении 2, что вы используете sAutoWidth
, но я думаю, что вы опечатали bAutoWidth
. Попробуйте изменить это.
Вы также можете добавить правило CSS в .table
если проблема не .table
.
Также следует соблюдать осторожность, когда ширина содержимого превышает заголовок столбца.
Итак, что-то вроде комбинации 1 и 2:
$('.table').dataTable({
bAutoWidth: false,
aoColumns : [
{ sWidth: '15%' },
{ sWidth: '15%' },
{ sWidth: '15%' },
{ sWidth: '15%' },
{ sWidth: '15%' },
{ sWidth: '15%' },
{ sWidth: '10%' }
]
});
Ответ 2
вы должны использовать
"bAutoWidth
" свойства datatable и укажите ширину для каждого столбца td/column в%
$(".table").dataTable({"bAutoWidth": false ,
aoColumns : [
{ "sWidth": "15%"},
{ "sWidth": "15%"},
{ "sWidth": "15%"},
{ "sWidth": "15%"},
{ "sWidth": "15%"},
{ "sWidth": "15%"},
{ "sWidth": "10%"},
]
});
Надеюсь, это поможет.
Ответ 3
Мой способ сделать это
$('#table_1').DataTable({
processing: true,
serverSide: true,
ajax: 'customer/data',
columns: [
{ data: 'id', name: 'id' , width: '50px', class: 'text-right' },
{ data: 'name', name: 'name' width: '50px', class: 'text-right' }
]
});
Ответ 4
Я бы предложил не использовать пиксели для sWidth, а использовать проценты. Как ниже:
"aoColumnDefs": [
{ "sWidth": "20%", "aTargets": [ 0 ] }, <- start from zero
{ "sWidth": "5%", "aTargets": [ 1 ] },
{ "sWidth": "10%", "aTargets": [ 2 ] },
{ "sWidth": "5%", "aTargets": [ 3 ] },
{ "sWidth": "40%", "aTargets": [ 4 ] },
{ "sWidth": "5%", "aTargets": [ 5 ] },
{ "sWidth": "15%", "aTargets": [ 6 ] }
],
aoColumns : [
{ "sWidth": "20%"},
{ "sWidth": "5%"},
{ "sWidth": "10%"},
{ "sWidth": "5%"},
{ "sWidth": "40%"},
{ "sWidth": "5%"},
{ "sWidth": "15%"}
]
});
Надеюсь, что это поможет.
Ответ 5
Вы можете определить sScrollX : "100%"
, чтобы заставить dataTables сохранять ширину столбцов:
..
sScrollX: "100%", //<-- here
aoColumns : [
{ "sWidth": "100px"},
{ "sWidth": "100px"},
{ "sWidth": "100px"},
{ "sWidth": "100px"},
{ "sWidth": "100px"},
{ "sWidth": "100px"},
{ "sWidth": "100px"},
{ "sWidth": "100px"},
],
...
вы можете играть с этой скрипкой → http://jsfiddle.net/vuAEx/
Ответ 6
Это единственный способ заставить его работать:
JS:
columnDefs: [
{ "width": "100px", "targets": [0] }
]
CSS
#yourTable{
table-layout: fixed !important;
word-wrap:break-word;
}
Часть CSS не хороша, но выполняет эту работу.
Ответ 7
Я устанавливаю ширину столбцов в разметке HTML следующим образом:
<thead>
<tr>
<th style='width: 5%;'>ProjectId</th>
<th style='width: 15%;'>Title</th>
<th style='width: 40%;'>Abstract</th>
<th style='width: 20%;'>Keywords</th>
<th style='width: 10%;'>PaperName</th>
<th style='width: 10%;'>PaperURL</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr id="@item.ID">
<td>@item.ProjectId</td>
<td>@item.Title</td>
<td>@item.Abstract</td>
<td>@item.Keywords</td>
<td>@item.PaperName</td>
<td>@item.PaperURL</td>
</tr>
}
</tbody>
</table>
Ответ 8
для тех, кто по-прежнему имеет проблемы с 1.9.4
изменение
//oSettings.aoColumns[i].nTh.style.width = _fnStringToCss(oSettings.aoColumns[i].sWidth);
oSettings.aoColumns[i].nTh.style.minWidth = _fnStringToCss(oSettings.aoColumns[i].sWidth);
Ответ 9
Если вам когда-нибудь понадобится установить ширину столбца с данными с помощью ТОЛЬКО CSS, вам поможет следующее css :-)
HTML
<table class="table table-striped table-bordered table-hover table-checkable" id="datatable">
<thead>
<tr role="row" class="heading">
<th width="2%">
<label class="mt-checkbox mt-checkbox-single mt-checkbox-outline">
<input type="checkbox" class="group-checkable" data-set="#sample_2 .checkboxes" />
<span></span>
</label>
</th>
<th width=""> Col 1 </th>
<th width=""> Col 2 </th>
<th width=""> Col 3 </th>
<th width=""> Actions </th>
</tr>
<tr role="row" class="filter">
<td> </td>
<td><input type="text" class="form-control form-filter input-sm" name="col_1"></td>
<td><input type="text" class="form-control form-filter input-sm" name="col_2"></td>
<td><input type="text" class="form-control form-filter input-sm" name="col_3"></td>
<td>
<div class="margin-bottom-5">
<button class="btn btn-sm btn-success filter-submit margin-bottom"><i class="fa fa-search"></i> Search</button>
</div>
<button class="btn btn-sm btn-default filter-cancel"><i class="fa fa-times"></i> Reset</button>
</td>
</tr>
</thead>
<tbody> </tbody>
</table>
Используя тему администрирования metronic и мой идентификатор таблицы #datatable, как указано выше.
CSS
#datatable > thead > tr.heading > th:nth-child(2),
#datatable > thead > tr.heading > th:nth-child(3) { width: 120px; min-width: 120px; }
Ответ 10
Я пытался во многих отношениях. Единственный способ, который работал для меня, был:
Решение Yush0 CSS:
#yourTable{
table-layout: fixed !important;
word-wrap:break-word;
}
Вместе с Роем Джексоном HTML Solution:
<th style='width: 5%;'>ProjectId</th>
<th style='width: 15%;'>Title</th>
<th style='width: 40%;'>Abstract</th>
<th style='width: 20%;'>Keywords</th>
<th style='width: 10%;'>PaperName</th>
<th style='width: 10%;'>PaperURL</th>
</tr>