DIV CSS 佈局教程網

jQuery 實現長文字部分顯示與展開收合效果
編輯:JQuery特效代碼     

網頁上版面空間有限,但說明文字很長該怎麼辦?本文示範如何只顯示部分文字,並透過點擊「展開/合起」按鈕來切換完整內容,還帶有平滑的高度動畫。

原本想用 jQuery 自帶的 toggle() 來寫,但實作時一直不 work,於是改用 click 加上標誌位的方式來控制狀態。

核心腳本

做法是先記錄原始文字與高度,再把內容截切成指定字數;點擊時透過 cur_status 標誌位判斷目前是展開還是收合狀態,並用 animate 做高度過渡:

<script language="javascript">
var cur_status = "less";
$.extend({
show_more_init: function(){
var charNumbers = $(".content").html().length; // 總字數
var limit = 100; // 顯示字數
if (charNumbers > limit)
{
var orgText = $(".content").html();   // 原始文本
var orgHeight = $(".content").height(); // 原始高度
var showText = orgText.substring(0, limit); // 最終顯示的文本
$(".content").html(showText);
var contentHeight = $(".content").height(); // 截取後的高度
$(".switch").click(
function() {
if (cur_status == "less"){
$(".content").height(contentHeight).html(orgText).animate({ height: orgHeight}, { duration: "slow" });
$(this).html("合起");
cur_status = "more";
} else {
$(".content").height(orgHeight).html(showText).animate({ height: contentHeight}, { duration: "fast" });
$(this).html("展開");
cur_status = "less";
}
}
);
}
else
{
$(".switch").hide();
}
}
});
$(document).ready(function(){
$.show_more_init();
});
</script>

HTML 結構

內容放在 .content 中,切換按鈕放在 .switch:

<div id="limittext">
<div class="content" style="padding-bottom:15px;">
這裡放入很長的一段文字……
</div>
<div class="switch">展開</div>
</div>

若文字本來就沒超過設定字數,.switch 按鈕會自動隱藏,避免出現多餘的展開提示。這個模式在部落格摘要、新聞列表等場景中非常實用。

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