Vue textarea 高度自適應


Vue textarea 高度自適應

  • 主要用到兩個屬性offsetHeight,scrollHeight
  • scrollHeight 是內容的滾動高度,包含沒實現出來的
  • offsetHeight 當前控件顯示的高度,如果文字增多了,不做自適應,這個高度不變,scrolHeight變大,所以可以比較這兩個值,修改textarea的高度后,offsetHeight也就變了。

<template>
  <div>
    <div class="address-container">
      <label>當前地址</label>
      <textarea ref="test" class="textarea-mine" v-model="currentValue"></textarea>
    </div>
  </div>
</template>
<script type="text/javascript">
  export default {
    data () {
      return {
        currentValue: ''
      }
    },
    watch: {
      currentValue (nv, ov) {
        if (nv === ov) {
          return
        }
        this.currentValue = nv
        console.log('value changed')
        this.changeHeight()
      }
    },
    methods: {
      changeHeight () {
        let _this = this
        this.$nextTick(() => {
          var textArea = _this.$refs.test
          var scrollHeight = textArea.scrollHeight // 控件所有的高度,包含滾動的那部分(不可見也會有高度)
          var height = textArea.offsetHeight // 屏幕上顯示的高度
          if (height <= scrollHeight) {
            textArea.style.height = 'auto' // 恢復默認值,這個作用就是根據內容自適應textarea高度
            textArea.style.height = textArea.scrollHeight + 'px' // 拿到最新的高度改變textarea的高度
          }
        })
      }
    }
  }
</script>

<style scoped>

  .address-container {
    position: relative;
    display: flex;
    align-items: center;
    font-size: 15px;
  }

  .address-container label {
    min-width: 4rem;
    margin: 0px 5px;
  }

  .textarea-mine {
    min-height: 20px;
    padding: 5px;
    width: 100%;
    display: block;
    flex: 1;
    margin: 10px 5px;
    font-size: 15px;
    color: #0c0c0c;
    outline: none;
    border: none;
    overflow-y: auto;
    appearance: none;
    text-align: inherit;
    font-family: -apple-system-font, "Helvetica Neue", sans-serif, "Microsoft YaHei";
  }
</style>

  • 參考
scrollHeight: ENTIRE  content & padding (visible or not)
Height of all content + paddings, despite of height of the element.

clientHeight: VISIBLE content & padding
Only visible height: content portion limited by explicitly defined height of the element.

offsetHeight: VISIBLE content & padding + border + scrollbar
Height occupied by the element on document.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM