LoginSignup
33
28

More than 5 years have passed since last update.

textareaの高さを入力内容によって可変したい

Last updated at Posted at 2019-02-19

やりたいこと

textareaの高さを入力内容によって可変したい

改行したり、文字が折り返したりしたら、スクロールになるのではなく、
textareaheightが長くなったり短くなったりして、スクロールしなくても入力した文字が見えるようにしたい。

textareavalueを取得して、改行コードの数を調べて、
改行の数*行間+余白textareaheightにするという方法を見つけたが、
文字が折り返した時には対応できないので、すごく不完全でいやだなぁ〜と思っていたら、
普通にあった(゜ロ゜)

scrollHeight

これで、スクロールしているtextareaheightが取れるので、あとはstyle.heighttextareaheightを変更するだけ。

なんて簡単なんだ。(なんで知らなかったの?)

しかし、文字にするとわかりにくいw

コード

Vue.jsで書いてたので、Vue.jsの書き方です。
省略して該当部分だけ書きます。

<textarea ref="adjust_textarea" @keydown="adjustHeight" v-model="textareaVal"></textarea>
methods: {
  adjustHeight(){
    const textarea = this.$refs.adjust_textarea
    const resetHeight = new Promise(function(resolve) {
      resolve(textarea.style.height = 'auto')
    });
    resetHeight.then(function(){
      textarea.style.height = textarea.scrollHeight + 'px'
    });
  }
}

軽く解説

改行や文字の折り返しで、長くなるだけなら

textarea.style.height = textarea.scrollHeight + 'px'

だけで大丈夫だけど、改行を消した時などに、短くもなって欲しいので、

textarea.style.height = 'auto'

で、一度高さをリセットして、新たに高さを取得する。
その時、ちゃんと高さがautoになってから、高さを再取得したいので、promiseを使う。

もし、他で何かしたらtextareaの内容が変わり、その時にも高さの調節をしたい場合は、watchする。

watch: {
  textareaVal() {
    this.adjustHeight();
  }
}
33
28
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
33
28