當列表或卡片中的文字過長時,我們往往希望它「超出部分省略並顯示省略號」。本文介紹兩種實用做法:一種純靠 CSS,另一種用 JavaScript,兩者都能在含 HTML 標籤的內容中正常運作。
這種方式相容於 IE、FireFox、Opera、Safari,設定寬高並搭配 text-overflow: ellipsis 即可:
.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>
如果需要更精細的控制(例如針對表格儲存格),可以用 jQuery 擴充一個 substr 方法:
<HTML>
<HEAD>
<TITLE>JQUERY 文本截取方法</TITLE>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<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>
</HEAD>
<BODY onload="javascript:subTdContent();">
<table style="border:1px solid #b3c0f5;" border="1">
<tr>
<td>我是代碼:$.fn.substr = function(l,c){ $(this).each(function(i,item)</td>
<td>以下兩種方式都可以解決textarea行高自動適應類容的高度</td>
<td>以下兩種方式都可以解決textarea行</td>
</tr>
</table>
</BODY> </HTML>
CSS 方案簡單、效能佳,適合單純的文字截斷;而 JavaScript 方案更靈活,能自訂截斷長度與省略符號,並可批量處理多個元素。根據實際場景挑選合適的方法,就能兼顧美觀與效能。