Home > Article > Web Front-end > An implementation method for automatically allocating column widths in data tables
layui data table automatically allocates column width renderings:
Applicable scenarios:
Mainly solves the problem of blank and blank spaces at the end of the table after the window size is changed. Scroll bar problem
-The window changes from small to large, and the last column of the table appears blank
The window changes from large to small, and the horizontal scroll bar appears
Reload Return to normal after the frame
Prerequisites for use:
-The header of each column must be set to minWidth (judgment based on the minWidth attribute)
-Use it by yourself
-The page can only have one data table. If there are multiple data tables, you need to modify the code yourself (judgment of the table, acquisition of column number, etc.)
Specific steps:
-Listen to the window size change event
var resizeTimer; $(window).resize(function () { if (resizeTimer) { clearTimeout(resizeTimer); } resizeTimer = setTimeout(function () { resizeTimer = null; dstributionColumnWidth(); }, 200); }); /* 经过测试发现,当窗口大小改变之后,这个方法会调用多次 所以需要使用clearTimeout方法取消由 setTimeout() 方法设置的 timeout 也就是说每一次调用后200毫秒内的下一次调用都会取消上一次的调用 这样可以大概率保证最终只执行一次 如果还是不行就把200调大点比如500 当然值越小,给人的感觉越流畅 */
Get the width and number of columns of the table, and find the average column width
// 表格宽度 var tabWidth = $(".layui-table-header").width(); // 列数 var colNum = $("tr").eq(0).find("th").length; // 平均列宽 var avgWidth = tabWidth / colNum; /* 求宽度和列宽的方式比较简单,也不知道有没有通用性(水平所限), 自己使用没有问题,如果大家拿不到值的话就根据自己的情况写代码拿到相应的值就行了, 当然要是有更好更优雅的方法也一定要留言告诉我 */
Get the data-field of each column and the value of the data-minwidth attribute and encapsulate it as an object, and sort it from large to small according to the value of data-minwidth
/** * 列对象 * @param index 所在列在当前行中的索引位置(没用上可以不要) * @param name 对应表头中设置的field * @param minWidth 对象表头中的minWidth * @param width 最终的宽度 * @constructor */ function Column(index, name, minWidth, width) { this.index = index; this.name = name; this.minWidth = minWidth; this.width = width; } // 获取参数封装对象 if (cols === undefined) { cols = $("tr").eq(0).find("th").map(function (index, item) { var col = new Column(index, $(this).attr("data-field"), $(this).attr("data-minwidth")); return col; }); // 排序 cols.sort(function (a, b) { return b["minWidth"] - a["minWidth"]; }); } /** * 计算列宽 * @param columns column对象数组 * @param colNum 列数 * @param tabWidth 表格宽度 * @param avgWidth 平均宽度 */ function calculateColumnWidth(columns, colNum, tabWidth, avgWidth) { // 是否显示表格横向滚动条 showOverflowX = false; // 是否完成比较 var isComplete = false; for (var i = 0; i < columns.length; i++) { var column = columns[i]; // 如果计算出的平均列宽比最大的minWidth还要大,那么剩下的就不用比较了,直接赋值即可 if (column["minWidth"] <= avgWidth || isComplete) { column["width"] = parseInt(avgWidth); isComplete = true; } else { /* 如果minWidth > 平均列宽,那么就用表格宽度减去minWidth 然后除以列数-1,重新求平均列宽 */ column["width"] = column["minWidth"]; tabWidth -= column["minWidth"]; colNum -= 1; avgWidth = tabWidth / colNum; // 如果最后一列时,平均列宽大于最小列宽,说明当前页面的宽度足够显示表格,就可以隐藏横向滚动条,反之则需要显示滚动条 if (i == columns.length - 1) { showOverflowX = true; } } } }
Set the cell width and set the scroll bar
// 这里是根据名称查找相应的th、td标签,可能有更好的方法,欢迎留言 for (var i = 0; i < cols.length; i++) { var col = cols[i]; var width = cols[i].width; $("[data-field='" + cols[i]["name"] + "']").each(function () { // 实际修改的是th、td下的div标签 // 我使用的是动画的方式,也可以选择直接赋值 $(this).children().eq(0).animate({width: width}, 200); }) } // 根据showOverflowX的值判断是否需要显示滚动条 if (showOverflowX) { $('.layui-table-body').css({"overflow-x": "auto"}); } else { $('.layui-table-body').css({"overflow-x": "hidden"}); }
Complete!
Complete code
var cols, showOverflowX; /** * 列对象 * @param index 所在列在当前行中的索引位置(没用上可以不要) * @param name 对应表头中设置的field * @param minWidth 对象表头中的minWidth * @param width 最终的宽度 * @constructor */ function Column(index, name, minWidth, width) { this.index = index; this.name = name; this.minWidth = minWidth; this.width = width; } /** * 计算列宽 * @param columns column对象数组 * @param colNum 列数 * @param tabWidth 表格宽度 * @param avgWidth 平均宽度 */ function calculateColumnWidth(columns, colNum, tabWidth, avgWidth) { showOverflowX = false; var isComplete = false; for (var i = 0; i < columns.length; i++) { var column = columns[i]; if (column["minWidth"] <= avgWidth || isComplete) { column["width"] = parseInt(avgWidth); isComplete = true; } else { column["width"] = column["minWidth"]; tabWidth -= column["minWidth"]; colNum -= 1; avgWidth = tabWidth / colNum; if (i == columns.length - 1) { showOverflowX = true; } } } } /** * 分配列宽 */ function dstributionColumnWidth() { // 表格宽度 var tabWidth = $(".layui-table-header").width(); // 列数 var colNum = $("tr").eq(0).find("th").length; // 平均列宽 var avgWidth = tabWidth / colNum; if (cols === undefined) { cols = $("tr").eq(0).find("th").map(function (index, item) { var col = new Column(index, $(this).attr("data-field"), $(this).attr("data-minwidth")); return col; }); cols.sort(function (a, b) { return b["minWidth"] - a["minWidth"]; }); } calculateColumnWidth(cols, colNum, tabWidth, avgWidth); for (var i = 0; i < cols.length; i++) { var col = cols[i]; var width = cols[i].width; $("[data-field='" + cols[i]["name"] + "']").each(function () { $(this).children().eq(0).animate({width: width}, 200); }) } if (showOverflowX) { $('.layui-table-body').css({"overflow-x": "auto"}); } else { $('.layui-table-body').css({"overflow-x": "hidden"}); } } var resizeTimer; $(window).resize(function () { if (resizeTimer) { clearTimeout(resizeTimer); } resizeTimer = setTimeout(function () { resizeTimer = null; dstributionColumnWidth(); }, 200); });
Usage method
layui.config({ // 放到这个目录里 base: '/static/js/extend/' }).extend({formSelects: 'formSelects-v4.min'}); // 这里 layui.use(['table', 'element', 'layer', 'jquery', 'form', 'formSelects', 'tools', 'autoColumnWidth'], function () { var table = layui.table, element = layui.element, layer = layui.layer, $ = layui.$, form = layui.form, formSelects = layui.formSelects, tools = layui.tools, // 这里 autoColumnWidth = layui.autoColumnWidth;
Then call it directly where needed
autoColumnWidth.resize();
ps: The window size monitoring code still needs to be written by yourself
If you want to allocate column width after the data table is loaded, you can write it in the callback of done
done: function () { autoColumnWidth.resize(); }
Recommended: layui usage tutorial
The above is the detailed content of An implementation method for automatically allocating column widths in data tables. For more information, please follow other related articles on the PHP Chinese website!