萬盛學電腦網

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

JS 與 CSS 限制文字顯示長度的多種方案

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 插件功能豐富、全瀏覽器兼容、可自定義邏輯需額外代碼、重排重繪開銷複雜截斷邏輯、舊瀏覽器兼容

最佳實踐建議

  1. 優先使用 CSS 方案,性能最優
  2. 多行截斷需兼容 Firefox/Edge 時,使用 -webkit-line-clamp 配合 @supports 降級
  3. 動態內容建議在渲染後統一處理,避免重複計算
  4. 保留原始文本用於無障礙讀屏或 tooltip 顯示完整內容
copyright © 萬盛學電腦網 all rights reserved