You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于jQuery实现DataTables表格列可拖拽调整宽度功能的问题求助

DataTables列宽拖拽调整可行解决方案
  • 第一步:修正CSS配置,必须开启table-layout: fixed,该属性是列宽拖拽生效的核心前提,同时补充拖拽手柄的可识别样式:
table, td, th {
    table-layout: fixed; /* 取消原注释,必须开启 */
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}
/* 补充拖拽手柄样式,避免被表头内容遮挡 */
.ui-resizable-handle.ui-resizable-e {
    width: 8px;
    height: 100%;
    right: 0;
    top: 0;
    position: absolute;
    cursor: col-resize;
    z-index: 100;
}
th {
    position: relative;
}
  • 第二步:调整DataTables配置,解决重复绑定和列宽不同步问题:
    1. 关闭responsive: true,该属性会自动适配列宽,和手动拖拽逻辑冲突,若需要响应式能力可自行额外适配
    2. drawCallback中先销毁已存在的resizable实例,再重新初始化,避免多次渲染重复绑定
    3. 拖拽结束后同步对应列所有单元格的宽度,保证整列宽度统一,同时更新DataTables内部宽度缓存
var table_option = {
    processing: true,
    serverSide: true,
    searching: false,
    responsive: false, // 关闭默认响应式,避免和拖拽冲突
    dom: "lfBtip",
    ajax: {
        url: '/get/textVal'
    },
    columns: [{
        data: null, // 修正原语法错误,去掉引号
        defaultContent: "<input type='checkbox' class='chkbox'>",
        orderable: false // 多选列禁止排序,避免点击排序和拖拽事件冲突
    },
    { data: 'test1' },
    { data: 'test2' },
    ],
    autoWidth: false,
    drawCallback: function(settings) {
        // 先销毁已有的resizable实例,避免重复绑定
        if ($('table th').hasClass('ui-resizable')) {
            $('table th').resizable('destroy');
        }
        // 重新初始化拖拽
        $('table th').resizable({
            handles: 'e',
            minWidth: 18,
            stop: function(e, ui) {
                const colIndex = $(this).index();
                // 同步整列的宽度,覆盖thead和tbody所有单元格
                $(`table tr td:nth-child(${colIndex + 1}), table tr th:nth-child(${colIndex + 1})`).width(ui.size.width);
                // 调整DataTables内部宽度缓存,避免重绘后宽度重置
                table.columns.adjust();
            }
        });
    }
}
// 初始化表格后赋值给全局table变量,供调整宽度使用
const table = $('#examTbl').DataTable(table_option);
  • 第三步:确认依赖引入顺序正确,必须按以下顺序引入资源:
    • jQuery核心库
    • jQuery UI核心库 + resizable组件
    • DataTables核心库

内容的提问来源于stack exchange,提问作者je2

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 14:24:04