CSS 純樣式方案(推薦)
單行文本截斷
.ellipsis-1 {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
width: 200px; /* 必須指定寬度 */
}
多行文本截斷(WebKit 內核)
.ellipsis-3 {
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 3; /* 顯示行數 */
overflow: hidden;
}
jQuery 插件方案(兼容舊瀏覽器)
(function($) {
$.fn.wordLimit = function(num) {
this.each(function() {
const $this = $(this);
const text = $this.text();
if (!num) {
// 自動模式:根據 CSS 寬度計算
const $clone = $this.clone().css({
position: 'absolute',
width: 'auto',
overflow: 'visible',
visibility: 'hidden'
}).appendTo('body');
if ($clone.width() > $this.width()) {
let truncated = text;
while ($clone.text(truncated + '...').width() > $this.width()) {
truncated = truncated.slice(0, -1);
}
$this.html(truncated + '...');
}
$clone.remove();
} else if (text.length > num) {
// 固定字符數模式
$this.html(text.substring(0, num) + '...');
}
});
return this;
};
})(jQuery);
// 使用方式
$('.nav_block span').wordLimit(); // 自動模式
$('.description').wordLimit(100); // 限制 100 字符
原生 JS 實現(無依賴)
function truncateText(element, maxLength, suffix = '...') {
if (element.textContent.length <= maxLength) return;
let truncated = element.textContent.substring(0, maxLength);
// 避免截斷單詞中間(英文場景)
const lastSpace = truncated.lastIndexOf(' ');
if (lastSpace > maxLength * 0.8) {
truncated = truncated.substring(0, lastSpace);
}
element.textContent = truncated + suffix;
}
// 使用
document.querySelectorAll('.truncate').forEach(el => truncateText(el, 50));
方案對比與選型建議
| 方案 | 優點 | 缺點 | 適用場景 |
| CSS 單行 | 性能最好、無 JS 依賴、自動響應寬度變化 | 僅支援單行 | 導航、標題、標籤 |
| CSS 多行 | 純 CSS、性能好 | 僅 WebKit 內核支援、無法自定義後綴位置 | 卡片摘要、文章預覽 |
| JS 插件 | 功能豐富、全瀏覽器兼容、可自定義邏輯 | 需額外代碼、重排重繪開銷 | 複雜截斷邏輯、舊瀏覽器兼容 |
最佳實踐建議
- 優先使用 CSS 方案,性能最優
- 多行截斷需兼容 Firefox/Edge 時,使用
-webkit-line-clamp 配合 @supports 降級
- 動態內容建議在渲染後統一處理,避免重複計算
- 保留原始文本用於無障礙讀屏或 tooltip 顯示完整內容