Angularjs angular 数据表更改 DTColumnDef 上的列宽

Angularjs angular datatables changing column width on DTColumnDef

版本:AngularJS1.6.4,angular-datatables0.5.6

问题:无法使用

更改列宽
.withOption('width', '20%')

我已经浏览了大部分 SO 问题,但仍未找到答案。

这是我的示例代码:

JS:

 $scope.dtOptions = DTOptionsBuilder.newOptions()
    .withOption('paging', false)
    .withOption('bInfo', false)
    .withOption('searching', false)
    .withScroller().withOption('scrollY', 300)
    .withOption('responsive', true)
    .withOption('scrollX', true)
    .withOption('scrollCollapse', true)
    .withOption("rowCallback", rowCallback)
    .withOption('autoWidth', true);


 $scope.dtColumnDefs = [
        DTColumnDefBuilder.newColumnDef(0).notSortable(),
        DTColumnDefBuilder.newColumnDef(1).notSortable(),
        DTColumnDefBuilder.newColumnDef(2),
        DTColumnDefBuilder.newColumnDef(3),
        DTColumnDefBuilder.newColumnDef(4),
        DTColumnDefBuilder.newColumnDef(5).notSortable(),
        DTColumnDefBuilder.newColumnDef(6).notSortable(),
        DTColumnDefBuilder.newColumnDef(7).notSortable(),
        DTColumnDefBuilder.newColumnDef(8).notSortable().withOption('width', '20%'),
        DTColumnDefBuilder.newColumnDef(9).notSortable(),
        DTColumnDefBuilder.newColumnDef(10).notSortable(), 
        DTColumnDefBuilder.newColumnDef(11).notSortable(),
        DTColumnDefBuilder.newColumnDef(12).notSortable(),
        DTColumnDefBuilder.newColumnDef(13).notSortable()
    ];

HTML:

 <table datatable="ng" dt-options="dtOptions" dt-column-defs="dtColumnDefs" class="hover">
            <thead>
                <tr>
                     <th><!--14 headers here--></th>
                </tr>
            </thead>
        <tbody>
                <tr>
                     <td><!--14 data cells here--></td>
                </tr>
       </tbody>
 </table>

我已经确认大多数带选项的 dtOptions 都工作正常,除了

 .withOption('autoWidth', true);

在 dtColumnDefBuilder 中,

 .notSortable() 

也工作正常,但

不行
.withOption('width','20%')

我尝试过的事情:

感谢您的帮助

如果您想推翻默认值和 DT 的假设,您 必须 明确声明 CSS class。 autoWidth 或多或少没用,恕我直言。示例:

.td-small {
  width: 40px;
  max-width: 40px;
}
DTColumnDefBuilder
 .newColumnDef(8)
 .notSortable()
 .withClass('td-small')

您可以组合 class 个,即 .withClass('classA classB classC')

即使文档讨论了百分比,它也只适用于非常狭窄的场景,即您将 所有 列设置为具有特定百分比 and将容器也设置为 固定 宽度,例如 900px。 "undefined" 的 20% 不计算。我在我的项目中可以找到的另一个典型示例是需要用省略号缩减的长内容:

.td-200-ellipsis {
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
}

如果您想对列宽进行极端控制,超出 DataTables 范围,请参阅此答案 ->