列表頁的摘要欄位經常需要「超過 N 字就切斷,尾巴補上省略號」。與其 foreach 寫死一份又一份的判斷,不如把它包成 jQuery 擴充方法,讓 HTML 用一個自訂屬性就能宣告每行顯示幾個字。
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>jQuery 字串截斷示範</title>
<script type="text/javascript" src="jquery-1.8.3.js"></script>
<style>
* { margin:0; padding:0; font-family:"\5b8b\4f53", Arial, Helvetica, sans-serif; }
#best { width:300px; height:200px; border:1px solid #ccc; margin:60px auto 0;
line-height:1.6; font-size:14px; padding:10px 0 0 10px; }
.blank { font-size:18px; font-weight:bold; text-align:center; padding:20px; }
</style>
<script type="text/javascript">
jQuery.fn.limit = function () {
var self = $("div[limit]");
self.each(function () {
var objString = $(this).text();
var objLength = objString.length;
var num = $(this).attr("limit");
if (objLength > num) {
$(this).attr("title", objString); // 滑過可看全文
$(this).text(objString.substring(0, num) + "...");
}
});
};
$(function () { $(document.body).limit(); });
</script>
</head>
<body>
<div id="best">
<div limit="12">計算字串的長度長度長度長度</div>
<div limit="10">這邊有優化很公開這邊</div>
<div limit="12">這邊有優化很公開長度長度很公開長度</div>
<div limit="12">計算字長度長度</div>
<div limit="10">這邊有優化很邊有優化很邊有優化很邊有優化很邊有優化很</div>
</div>
</body>
</html>
取得每個 div 的文字長度,與 limit 屬性宣告的門檻比較;超出者以 substring(0, num) 取前 N 字,再接上省略號,同時把完整內容寫進 title,讓使用者滑鼠移入時能看全文。
jQuery.fn.limit = function(){}:為 jQuery 增加一個實例方法,之後所有 jQuery 物件都能呼叫 .limit()。$("div[limit]"):以屬性存在性做過濾,一次撈出所有帶有 limit 的 div。.each(function(){...}):逐一走訪集合中的元素,回調裡的 this 指向當前 DOM 節點。$(this).text() 與 .length:取出純文字內容與其長度。$(this).attr("limit"):讀出自訂屬性值作為長度上限。.attr("title", objString):把完整字串放進原生 tooltip,零成本補上「看全文」的能力。.text(...) 取代原本的 .text() 回傳寫法:原範例寫成 objString = $(this).text(...),把回傳的 jQuery 物件又賦回字串變數,語意上多餘;直接呼叫 $(this).text(newValue) 即可。substring 以 UTF-16 碼元為單位,遇到 emoji 或罕用字可能切在代理對中間,產生亂碼。若要更嚴謹,可用 Array.from(str) 先轉為字元陣列再切片。overflow:hidden; text-overflow:ellipsis; white-space:nowrap; 一行 CSS 就能搞定,不必動到 DOM,也不必犧牲 SEO 與複製內容。多行則可用 -webkit-line-clamp。JavaScript 截斷的真正價值,在於你需要「實際長度」而非「視覺長度」的場合。