多行文字輸入框一旦內容變多就需要大量捲動,與其讓使用者自己拖曳右下角的小三角,不如提供一對「放大/縮小」按鈕。本文示範如何用 jQuery 的 animate() 做出平滑的高度變化。
關鍵只有一行:$Content.animate({height: "+=50"}, 400)。animate 支援以 += 與 -= 表示相對變化,因此不必先去讀取目前高度再計算,只要指定「增加多少」即可,並在 400 毫秒內平滑過渡。
<style type="text/css">
#Control { width: 100px; background-color: Red; margin: 0; cursor: pointer; }
</style>
<script src="jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
var $Content = $("#content");
$("#big").bind("click", function () {
// 避免動畫進行中重複觸發
if (!$Content.is(":animated") && $Content.height() < 400) {
$Content.animate({ height: "+=50" }, 400);
}
});
$("#smalll").bind("click", function () {
if (!$Content.is(":animated") && $Content.height() > 50) {
$Content.animate({ height: "-=50" }, 400);
}
});
});
</script>
HTML 部分只有一組控制列與一個 textarea:
<div id="Control">
<span id="smalll">縮小</span>
<span id="big">放大</span>
</div>
<div>
<textarea id="content" rows="8" cols="50">在這裡放入較長的文字內容</textarea>
</div>
第一,$Content.is(":animated") 是必要的防護。若使用者連續快速點擊,動畫會堆疊排隊,畫面看起來就會一頓一頓的。:animated 是 jQuery 提供的擴充選擇器,可以判斷元素目前是否正在播放動畫。
第二,加上上下界檢查(< 400 與 > 50)可以避免高度收縮到看不見或無限放大。若要更精確,可改用 Math.min() 計算目標值後一次設定,而不是累加。
如果希望 textarea 隨內容自動長高,也可以改用捲動高度來判斷:
$("#content").on("input", function () {
this.style.height = "auto";
this.style.height = this.scrollHeight + "px";
});
這段寫法不需要任何按鈕,內容變多時自動撐開,是許多現代聊天介面的做法,可視需求替換使用。