jquery数据表在初始化时设置宽度

jquery datatable set width upon initialization

本文关键字:设置 初始化 数据表 jquery      更新时间:2023-09-26

我试图在初始化时设置jQuery数据表中的单元格宽度,但它似乎永远不会起作用。我已经尝试过官方网站推荐的内容和其他例子。以下是我尝试过的一些选项。请帮帮我,我做错了什么?

例如:1

$('#dataTables-comments').DataTable({
    "bLengthChange": false,
    "bFilter": false,
    "iDisplayLength": 5,
    "aoColumns": [{
            "sWidth": "50%"
        }, 
        {
            "sWidth": null
        },  
        {
            "sWidth": null
        },   
        {
            "sWidth": null
        },   
        {
            "sWidth": null
        }   
    ],
    "responsive": true
});

例如:2

$('#dataTables-tbl').DataTable({
    "bLengthChange": false,
    "bFilter": false,
    "iDisplayLength": 5,
    "columnDefs": [{
        "width": "50%",
        "targets": 0
    }],
    "responsive": true
});

例如:3

$('#dataTables-tbl').DataTable({
    "bLengthChange": false,
    "bFilter": false,
    "iDisplayLength": 5,
    "columns": [{
        "width": "50%"
    }, {
        "width": "10%"
    }, {
        "width": "10%"
    }, {
        "width": "10%"
    }, {
        "width": "10%"
    }],
    "responsive": true
});

与CSS百分比值的任何其他用法一样,值必须是的百分比。如果表本身没有定义width,则10%是不可翻译的。所以给你的桌子一个width:

#dataTables-comments {
  width: 800px;
}

并确保关闭autoWidth,这样数据表就不会开始否决预定义的列宽:

$('#dataTables-tbl').DataTable({
    autoWidth: false, //<---
    "bLengthChange": false,
    "bFilter": false,
    "iDisplayLength": 5,
    "columns": [{
        "width": "50%"
    }, {
        "width": "10%"
    }, {
        "width": "10%"
    }, {
        "width": "10%"
    }, {
        "width": "10%"
    }],
    "responsive": true
});