導覽列或卡片標題若文字過長會破版,這時可以透過一個自訂的 jQuery 外掛 wordLimit 來自動截斷並加上省略號。以下示範如何套用,以及外掛本身的實作。
假設有這樣的導覽結構,每個 span 內是選單文字:
<nav class="cf_nav clearfix">
<ul>
<li><a href="#" title="首頁">
<div class="nav_block"><span>首頁</span><span class="hover">首頁</span></div>
</a></li>
<li><a href="#" title="投稿">
<div class="nav_block"><span>投稿</span><span class="hover">投稿</span></div>
</a></li>
</ul>
</nav>
要限制其中 span 的字數,只需呼叫:
$(".nav_block span").wordLimit(8);
這是從點點網整理而來的方法,不傳參數時會自動依 CSS 寬度判斷,傳入數字則以字數為準:
// copyright by zhangxinxu
// $(".test1").wordLimit(); 依 css 寬度自動處理
// $(".test2").wordLimit(24); 最多 24 個字
(function($){
$.fn.wordLimit = function(num){
this.each(function(){
if(!num){
var copyThis = $(this.cloneNode(true)).hide().css({
'position':'absolute', 'width':'auto', 'overflow':'visible'
});
$(this).after(copyThis);
if(copyThis.width() > $(this).width()){
$(this).text($(this).text().substring(0, $(this).text().length - 4));
$(this).html($(this).html() + '...');
copyThis.remove();
$(this).wordLimit();
} else {
copyThis.remove();
return;
}
} else {
var maxwidth = num;
if($(this).text().length > maxwidth){
$(this).text($(this).text().substring(0, maxwidth));
$(this).html($(this).html() + '...');
}
}
});
};
})(jQuery);
其巧思在於:不傳參數時,會先複製一份隱藏的節點來測量「若不限寬會有多寬」,再和實際容器寬度比較,超出就逐字削減直到放得下,最後補上省略號。傳入數字時則直接以字數截斷,簡單明快。