动态生成bootstrap-table表格过宽的问题

2024-03-20  本文已影响0人  阿乐_822e

当表格列数过度时,如果不做限制,表格会延伸到屏幕外,底部出现水平滚动条,看起来不美观,如果此时还要对表格内的数据进行编辑,就需要来回拖动滚动条,很不方便。
这里面涉及到两个问题,一个是表格标题文字过长时的换行处理,一个是表格内容过长时的换行处理

1、表格内容自动换行的处理

<table id="tmpTable" style="table-layout: fixed;word-break:break-all;" ></table>

像上面这定义表格,表格布局使用固定宽度fixed,可以保证表格不会溢出到屏幕以外;“word-break:break-all;”使得表格的内容过长时会自动换行,而不致于溢出到相邻单元格;

2、表格标题文字过长的处理

使用下面的自定义样式来修改th格式时,没有起到效果

th {
    white-space: normal;
}

这位老兄,也遇到了同样的问题:https://segmentfault.com/q/1010000018752913
那就强行换行

1、方法一,使用函数

... 
let cellLen = result.data.colTitles.length;
mycolumn.push({
                        field: fieldsss,
                        title: tableTitle(fieldsss,cellLen),
                        align: 'center',
                        valign: 'middle',
...
function tableTitle(title,cellLen) {
    let str = title;
    let splitValue = cellLen > 20 ? 4 : 7;
    if (str.length > splitValue) {
        let result = "";
        for (let i = 0; i < str.length; i++) {
            result += str[i];
            if ((i + 1) % splitValue === 0) {
                result += "<br>"; // 在第n个字符后添加换行标签
            }
        }
        return result;
    }
    return str;
}

这上面具体的分割长度可能需要根据实际情况调试一下。

2、方法二,在title中嵌入一个div(推荐)

修改上面的代码

mycolumn.push({
                        field: fieldsss,
                        /*title: fieldsss,*/
                        /*title: tableTitle(fieldsss,cellLen),*/
                        title: `<div style='white-space:nowrap;white-space: normal;word-break:break-all; word-wrap: break-word'>${fieldsss}</div>`,
......

因为th无法应用到自动换样式,就通过内嵌一个div来达到自动换行的效果

上一篇 下一篇

猜你喜欢

热点阅读