0.1 版只能把多餘的字換成省略符號,使用者想看完必須自己想辦法。0.2 版補上了展開/收合的能力,並允許在兩個狀態各掛一個回呼。
/**
* demo:
* 1. $("#limittext").limittext();
* 2. $("#limittext").limittext({"limit":1});
* 3. $("#limittext").limittext({"limit":1,"fill":"......","morefn":{"status":true}});
* 4. $("#limittext").limittext({"limit":1,"fill":"......","morefn":{
* "status":true,"moretext":"更多","lesstext":"隱藏部分",
* "fullfn":function(){alert("more")},"lessfn":function(){alert("less")}
* }})
* 5. $("#limittext").limittext({"limit":1,"fill":"......",
* "morefn":{"status":true}}).limit("all");
*
* @param {Object} opt
* @author Lonely
* @link https://www.liushan.net
* @version 0.2
*/
jQuery.fn.extend({
limittext: function(opt){
opt = $.extend({ "limit": 30, "fill": "..." }, opt);
opt.morefn = $.extend({
"status": false,
"moretext": "(more)",
"lesstext": "(less)",
"cssclass": "limittextclass",
"lessfn": function(){},
"fullfn": function(){}
}, opt.morefn);
var othis = this;
var $this = $(othis);
var body = $this.data('body');
// 完整原文存進 data,之後所有計算都以它為基準
if (body == null) {
body = $this.html();
$this.data('body', body);
}
// 產生「更多/隱藏」那顆連結
var getbuttom = function(showtext){
return "<a href='javascript:;' class='" + opt.morefn.cssclass + "'>"
+ showtext + "<a>";
};
this.limit = function(limit){
var showbody;
if (body.length <= limit || limit == 'all') {
showbody = body + (opt.morefn.status ? getbuttom(opt.morefn.lesstext) : "");
} else {
if (!opt.morefn.status) {
showbody = body.substring(0, limit) + opt.fill;
} else {
showbody = body.substring(0, limit) + opt.fill
+ getbuttom(opt.morefn.moretext);
}
}
$this.html(showbody);
};
this.limit(opt.limit);
// 用事件委派,因為那顆連結是動態產生的
$("." + opt.morefn.cssclass).live("click", function(){
if ($(this).html() == opt.morefn.moretext) {
showbody = body + getbuttom(opt.morefn.lesstext);
$this.html(showbody);
opt.morefn.fullfn();
} else {
othis.limit(opt.limit);
opt.morefn.lessfn();
}
});
return this;
}
});
live() 已被移除。這個方法在 jQuery 1.7 被標記為 deprecated,1.9 正式移除。新專案請改用 $(document).on('click', '.' + opt.morefn.cssclass, handler),寫法更清楚,效能也更好。
選擇器範圍太廣。$("." + opt.morefn.cssclass) 會抓到整個頁面上所有同 class 的元素。若同一頁掛了多個 limittext,點其中一顆會影響全部。正確作法是限定在自己的容器內:$this.on('click', '.' + cls, handler)。
標籤沒閉合。getbuttom 產生的結束標籤寫成 <a> 而非 </a>,同樣是 0.1 版留下來的問題,請一併修正。
showbody 缺少宣告。click 回呼裡的 showbody 沒有 var,會變成全域變數,多實例並存時容易互相干擾。
用 innerHTML 比對狀態不穩。判斷目前是展開還是收合,與其比對連結文字,不如維護一個 boolean 旗標,語意清楚也不受樣式影響。
打包下載:https://www.jb51.net/jiaoben/29345.html