利用textarea的scrollHeight属性动态改变textarea的高度实现自动换行

1、自定义指令

import Vue from 'vue';

Vue.directive('autoTextarea', {
  inserted: (el, binding) => {
    console.log(el);
    const change = () => {
      const value = el.value;
      // 内容长度不变不做处理
      if (el._length === value.length) return;
      el._length = value.length;
      let height;
      // textare单行高度
      let minHeight = binding.value ? binding.value.minHeight : 22;
      const style = el.style;
      const padding = parseInt(getComputedStyle(el)['paddingTop']) + parseInt(getComputedStyle(el)['paddingBottom']);
      style.overflowY = 'hidden';
      style.height = `${minHeight}px`;
      if (el.scrollHeight > minHeight) {
        height = el.scrollHeight - padding;
        style.height = `${height}px`;
      }
    }
    el.addEventListener('input', change);
    el.addEventListener('change', change);
  }
});

2、使用

<template>
   <div class="text">
     <h2>textarea自动换行</h2>
     <textarea class="textarea" v-autoTextarea="{minHeight: 26}"></textarea>
   </div>
</template>
<style scoped lang="scss">
.text {
  position: relative;
  .textarea {
    width: 240px;
    height: 26px;
    line-height: 26px;
    overflow: hidden;
    resize: none;
    background-color: #cccccc;
  }
}
</style>
Logo

前往低代码交流专区

更多推荐