スクロールが表示されているテキストエリアを、高さを調整しスクロール無しにする
2020年1月29日
Javascriptでスクロールが表示されているテキストエリアを、高さを調整しスクロール無しにする方法です。
//テキストエリアのHTML
<textarea name="ta" id="ta">
// jQueryの場合
$('textarea[name="ta"]').each(function () {
if ( this.scrollHeight > this.clientHeight ) {
$(this).height(this.scrollHeight);
}
});
// Javascriptの場合
var ta= document.getElementById("ta");
if ( ta.scrollHeight > ta.clientHeight ) {
ta.style.height = (ta.scrollHeight + 12) + 'px';// 12は適当
}
高さを短くする場合
上記だと、高さを伸ばすことしかできませんが、短くなった場合は以下のようにすればできそうです。
var ta= document.getElementById("ta");
if ( ta.scrollHeight === ta.clientHeight ) {
ta.style.height = 'auto';// 一度、高さをリセットする
}
ta.style.height = (ta.scrollHeight + 12) + 'px';