需求:內容少於四五行時不顯示任何按鈕;超過時截斷並附「顯示全部」,點擊後展開並變為「收起」。以下為完整可運行範例。
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript" src="js/jquery1.7.2.min.js"></script>
<title>查看更多---收起</title>
<style>
.z_content_right_two {
width: 978px; border: 1px solid #fff; padding: 10px;
font-size: 14px; color: #666666; margin: 20px auto;
text-indent: 30px; line-height: 22px; text-align: justify; background: #fff;
}
.ckgd {
color: #00b1bb; text-decoration: underline;
display: inline-block; margin-left: -27px;
}
.ckgd:hover { color: #00b1bb; text-decoration: none; }
</style>
</head>
<body>
<div class="z_content_right_two z_box_z">
在這裡放入大量文字內容,最多顯示五行,超過則出現「顯示全部」連結。
</div>
<div class="z_content_right_two z_box_z">
在這裡放入第二段內容,效果相同。
</div>
<script>
$(function () {
var max = 330; // 截斷長度
var display = "...顯示全部";
// 事件委派:展開/收起
$(".z_content_right_two").on("click", ".ckgd", function () {
var me = this,
show = $(me).text() == display,
attr = show ? "his" : "sub", // 要取回的內容
name = show ? "收起" : display; // 按鈕文字
$(this).parent().each(function () {
$(this).html($(this).attr(attr))
.append($(me).clone(true).text(name));
});
});
// 初始化:過長則截斷並附加按鈕
$(".z_box_z").each(function () {
var me = this,
text = getElementText(me),
length = text.length,
sub = text.substr(0, max);
$(me).attr({ his: text, sub: sub }); // 完整與截斷版各存一份
if (length > max) {
$(me).html(sub);
$(me).append($("<a href='javascript:void(0)' class='ckgd'>".concat(display, "</a>")));
}
});
});
// 取出元素內所有文字節點(含後代)
function getElementText(e) {
var t = "";
e = e.childNodes || e; // 傳入元素則遍歷其子節點
for (var j = 0; j < e.length; j++) {
t += e[j].nodeType != 1 ? e[j].nodeValue : getElementText(e[j].childNodes);
}
return t;
}
</script>
</body>
</html>
初始化:遞迴取出純文字,寫入 his(完整)與 sub(截斷)兩個自訂屬性;長度未超過 max 就什麼都不做,按鈕自然不出現。
切換:依目前按鈕文字判斷是展開還是收起,決定要取 his 還是 sub,重寫內容後把按鈕文字反過來。
用行數而非字數判斷更貼近需求。原需求是「超過五行才顯示」,但程式用固定字數 330 當門檻——字型大小或視窗寬度一變,五行對應的字數就不同。若要精準做到「五行」,應比較 el.scrollHeight 與 lineHeight * 5 :
var $el = $(".z_box_z");
var lineHeight = parseInt($el.css("line-height"), 10);
if ($el[0].scrollHeight > lineHeight * 5) {
$el.addClass("clamp-5"); // 用 -webkit-line-clamp 收斂
}
用 data 取代自訂屬性。$(me).attr("his", ...) 會把整段內容寫進 HTML 屬性,內容一大就很笨重,也容易與 DOM 的其他操作衝突。改用 $(me).data("full", text) 存暫存資料更乾淨。
另外,href="javascript:void(0)" 已不建議使用;改用 <button type="button"> 並搭配 CSS 樣式,對鍵盤操作與螢幕閱讀器都更友善。若要純 CSS 解方,line-clamp 只能做到「截斷」而無法展開,因此展開/收起仍需 JS 介入。