DIV CSS 佈局教程網

用 CSS 與 jQuery 限制頁面文字顯示的字元長度
編輯:關於JavaScript     

版面設計時,常會遇到某些欄位文字過長而撐破配置的狀況。這裡示範如何用一個自製的 jQuery 外掛 wordLimit 來限制顯示字數,多餘的部分自動以省略號收尾。

以下是一段典型的導覽列結構:

<nav class="cf_nav clearfix">
<ul>
<li>
<a href="https://lizhuangs.18021051d350c3871c0a.tpl.diandian.com" title="首頁">
<div class="nav_block">
<span>首頁</span>
<span class="hover">首頁</span>
</div>
</a>
</li>
<li>
<a href="https://lizhuangs.18021051d350c3871c0a.tpl.diandian.com/submit" title="投稿">
<div class="nav_block">
<span>投稿</span>
<span class="hover">投稿</span>
</div>
</a>
</li>
</ul>
</nav>

若想限制上面 span 內的字元數,只要呼叫:

$("nav_block span").wordLimit(8);

以下是這個外掛的完整定義(靈感來自點點網):

// copyright c by zhangxinxu v1.0 2009-09-05
// https://www.zhangxinxu.com
/* $(".test1").wordLimit(); 自動獲取 css 寬度進行處理,若 css 未對 .test1 給定寬度則不起作用
$(".test2").wordLimit(24); 截取字元數,值為大於 0 的整數,這裡表示 class 為 test2 的標籤內最多 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);

不帶參數時,它會依 CSS 寬度自動判斷並逐步截短直到放得下;帶入數字時則直接以字數為準,兩種模式都能保持版面整齊,是處理文字溢出的好幫手。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved