萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery EasyUI DataGrid 動態計算行高與文字截斷實戰

需求背景

DataGrid 列顯示長文本時,需根據欄寬自動截斷並顯示省略號,同時根據內容高度動態調整行高,避免內容被切割或留白過大。

核心實作:formatter 函數動態計算

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最大顯示字元數自動計算,無需硬編碼

行高自適應:CSS 方案(推薦)

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>

進階:tooltip 顯示完整內容

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');
  }
});

fixWidth 輔助函數

function fixWidth(ratio) {
  return Math.ceil(document.documentElement.clientWidth * ratio);
}

// 視窗變化時重新計算(可選)
$(window).resize(function() {
  $('#dg').datagrid('resize');
  // 若欄寬依賴 fixWidth,需重新載入或手動調整 columns
});

總結

  • formatter 負責文字截斷與省略號,動態計算 maxChars 適應響應式欄寬
  • CSS 控制行高:height:auto + white-space:normal 讓內容自然換行
  • tooltip 提供完整內容查看,不犧牲空間
  • 字元寬度經驗值需根據實際字體微調,建議提取為常數
copyright © 萬盛學電腦網 all rights reserved