DataGrid 列顯示長文本時,需根據欄寬自動截斷並顯示省略號,同時根據內容高度動態調整行高,避免內容被切割或留白過大。
columns: [[
{
field: 'activitycontent',
title: '活動內容',
width: fixWidth(0.18), // 螢幕寬度 18%
align: 'center',
halign: 'center',
formatter: function(value, row, index) {
// 1. 若包含圖片標籤,直接顯示(假設已是完整 HTML)
if (value.indexOf('src') >= 0) {
return value;
}
// 2. 計算該欄可容納字元數
// 螢幕寬度 * 0.18 / 字元寬度(約11.5px) = 字元數
var colWidth = Math.ceil(document.documentElement.clientWidth * 0.18);
var charWidth = 11.5; // 經驗值:中文字體約 11.5px
var maxChars = Math.ceil(colWidth / charWidth);
// 3. 截斷並加省略號
if (row.activitycontent.length > maxChars) {
return row.activitycontent.substring(0, maxChars) + '..';
}
return row.activitycontent.substring(0, maxChars);
}
},
{ field: 'otherField', title: '其他', width: fixWidth(0.1) }
]]
| 參數 | 說明 | 調整建議 |
|---|---|---|
fixWidth(0.18) | 欄寬佔螢幕比例 | 根據實際佈局調整 |
charWidth: 11.5 | 單字元像素寬度 | 字體大小變更時需同步調整 |
maxChars | 最大顯示字元數 | 自動計算,無需硬編碼 |
formatter 僅處理文字截斷,行高由 CSS 控制更可靠:
<style>
.datagrid-row {
height: auto !important; /* 覆蓋 EasyUI 固定行高 */
}
.datagrid-cell {
white-space: normal !important; /* 允許換行 */
word-wrap: break-word;
word-break: break-all;
line-height: 1.4;
padding: 4px 6px;
}
</style>
formatter: function(value, row, index) {
var maxChars = 30; // 或動態計算
var display = value.length > maxChars
? value.substring(0, maxChars) + '..'
: value;
// 滑鼠懸停顯示完整內容
return '<span title="' + value.replace(/"/g, '"') + '">'
+ display + '</span>';
}
$('#dg').datagrid({
columns: [[
{ field: 'id', title: 'ID', width: 50, align: 'center' },
{
field: 'content',
title: '內容',
width: fixWidth(0.4),
formatter: function(val, row) {
if (!val) return '';
var maxChars = Math.ceil($('.datagrid-view').width() * 0.4 / 12);
return val.length > maxChars
? '<span title="' + val.replace(/"/g, '"') + '">'
+ val.substring(0, maxChars) + '..</span>'
: val;
}
},
{ field: 'time', title: '時間', width: fixWidth(0.15), align: 'center' }
]],
onLoadSuccess: function() {
// 載入後觸發行高重計算(EasyUI 1.5+)
$(this).datagrid('fixRowHeight');
}
});
function fixWidth(ratio) {
return Math.ceil(document.documentElement.clientWidth * ratio);
}
// 視窗變化時重新計算(可選)
$(window).resize(function() {
$('#dg').datagrid('resize');
// 若欄寬依賴 fixWidth,需重新載入或手動調整 columns
});
maxChars 適應響應式欄寬height:auto + white-space:normal 讓內容自然換行