列表頁的摘要欄位有限,長標題或長內文需要截斷加省略號。本文提供 CSS 與 JS 兩種方案,前者適合純文字,後者能處理含 HTML 標籤的內容。
.subLongText{
width:150px;
height:24px;
overflow:hidden;
white-space:nowrap;
text-overflow:ellipsis;
text-overflow: ellipsis;/* IE/Safari */
-ms-text-overflow: ellipsis;
-o-text-overflow: ellipsis;/* Opera */
-moz-binding: url("ellipsis.xml#ellipsis");/*FireFox*/
}
<span class="subLongText">任意長度文本</span>
四個屬性缺一不可:overflow:hidden 隱藏溢出、white-space:nowrap 強制單行、text-overflow:ellipsis 產生省略號,寬度則決定截斷位置。作者提到這組寫法在 IE、Firefox、Opera、Safari 都能work——其中 -moz-binding 那行是 Firefox 2 時代的 XBL 綁定 hack,現代版本早已移除,現在只要前四行就足夠。
若需要限制行數而非寬度,用 line-clamp:
.subLongText {
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
}
<script type="text/javascript" src="jquery-1.3.2.js"></script>
<script type="text/javascript">
$.fn.substr = function(length,content){
$(this).each(function(i,item){
var val=$(item).html();
if(!val) return;
if(val.length>length) {
val = val.substring(0,length);
val += content || "..."
$(item).html(val);
}
});
}
function subTdContent(){
$('td').substr(20);
}
</script>
<table border="1">
<tr>
<td>我是代碼:$.fn.substr = function(l,c){ $(this).each(function(i,item)</td>
<td>以下兩種方式都可以解決textarea行高自動適應內容的高度</td>
<td>以下兩種方式都可以解決textarea行</td>
</tr>
</table>
作者說「含 HTML 代碼同樣適用」,但這個實作其實會破壞 HTML。它直接對 .html() 的字串做 substring(0, 20),很可能切在標籤中間,產生 <div class= 這種破碎標籤,後續會讓整頁排版跑掉。此外它也不處理 HTML 實體( 被切一半就成了亂碼)。
要正確處理含標籤的截斷,需要遍歷文字節點(Node.TEXT_NODE)累加長度,在切斷處收起所有開啟中的元素。這個邏輯並不簡單,成熟方案(如 ellipsis.js、clamp.js)都做了不少功課。
優先用 CSS。純文字用 text-overflow,多行用 line-clamp,都不需要 JS、不會閃爍、也不影響 SEO(完整內容仍在 DOM 中)。
含 HTML 的摘要最好在後端處理。用伺服器端的 HTML 解析器(如 Python 的 BeautifulSoup、Node 的 cheerio)先取出純文字再截斷,前端只負責顯示,安全又可靠。
若要 JS 截斷,別用 .html() 拼接。改用 textContent 操作,或引入專門的 clamp 函式庫。同时記得:$.fn.substr 這種擴充 jQuery 原型的做法會污染全域命名空間,容易與其他外掛衝突,建議改用獨立函式。
最後,別忘了提供完整內容的取用方式——title 屬性做 tooltip 是最簡單的做法,行動裝置上則建議點擊展開。