網頁設計:文字區域 (textarea) 自動高度調整
文字區域 (textarea) 自動高度調整文字區域 (textarea) 輸入文字超過設定的行數後,就會出現滾軸視窗。若想讓文字區域的高度隨著輸入文字行數自動調整,找來二種方法供參考之:
範例程式碼(jQuery):此法簡潔方便好用^^
紅色字部份。本小站下載: 含 Bootstrap 3.3.7 ~ 4.3.1 & jQuery 1.11.3 ~ 3.4.1
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>網頁設計:文字區域 (textarea) 自動高度調整</title>
<script src="js/jquery-3.2.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
jQuery(function($) {
$("textarea.AutoHeight").css("overflow","hidden").bind("keydown keyup", function(){
$(this).height('0px').height($(this).prop("scrollHeight")+"px");
}).keydown();
});
</script>
</head>
<body>
<p><textarea class="AutoHeight"></textarea></p>
<p>文字區域內已有文字的情形下(再輸入跳行試試):<br><textarea class="AutoHeight">第1行
第2行
第3行
第4行</textarea></p>
</body>
</html>
文字區域內已有文字的情形下(再輸入跳行試試):
範例程式碼(script):
紅色字部份。<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>網頁設計:文字區域 (textarea) 自動高度調整</title>
<script>
function autogrow(textarea){
var adjustedHeight=textarea.clientHeight;
adjustedHeight=Math.max(textarea.scrollHeight,adjustedHeight);
if (adjustedHeight>textarea.clientHeight){
textarea.style.height=adjustedHeight+'px';
}
}
</script>
</head>
<body>
<p><textarea onkeyup="autogrow(this);"></textarea></p>
<p>文字區域內已有文字的情形下(再輸入跳行試試):<br><textarea onkeyup="autogrow(this);">第1行
第2行
第3行
第4行</textarea></p>
</body>
</html>
文字區域內已有文字的情形下(再輸入跳行試試):