如何创建完美的自动调整大小的textarea?

时间:2019-01-15 19:27:59

标签: vue.js

我会自动扩展文本区域。

原理是这样的:我创建了一个隐藏的div,在其中放置了输入文本,然后在update()方法中定义了div的高度并将其值应用于文本区域。

但是有一个问题-出现文本抽动,因为首先,文本会向上爬,然后在扩展字段时,它会返回其位置。好像update()方法工作到很晚。出于同样的原则,我在ReactJS中创建了一个文本字段,没有这种效果。

该怎么办?

工作方式:https://jsbin.com/zakavehewa/1/edit?html,css,js,console,output

<template>
  <div class="textarea_wrap">
    <textarea class="text_input textarea" v-model="value" ref="textarea"></textarea>
    <div v-if="autoRow" class="text_input textarea shadow" ref="shadow">{{ value }}!</div>
  </div>
</template>

<script>
  export default {
    props: {
      autoRow: {
        type: Boolean,
        default: false
      },
      default: String
    },
    data () {
      return {
        value: this.default,
      }
    },
    mounted() {
      this.updateHeight()
    },
    updated() {
      this.updateHeight()
    },
    methods: {
      updateHeight() {
        if (this.autoRow && this.$refs.shadow) {
          this.$refs.textarea.style.height = this.$refs.shadow.clientHeight + 5 + 'px'
        }
      }
    }
  }
</script>

<style lang="scss" scoped>
  .textarea_wrap {
    position: relative;
  }

  .textarea {
    line-height: 1.5;
    min-height: 31px;
    width: 100%;    
    font-family: inherit;    
  }

  .shadow {
    position: absolute;
    left: -9999px;
    pointer-events: none;
    white-space: pre-wrap;
    word-wrap: break-word;
    resize: none;
  }
</style>

1 个答案:

答案 0 :(得分:0)

结帐https://github.com/wrabit/vue-textarea-autogrow-directive,它可以在隐藏的div中进行渲染以及复制和粘贴文本。