输入框如何自动伸缩及换行?

请问各位大神怎么实现这个效果, 输入长度变长时 自动伸缩输入框,超出行宽时自动换行

image.png

阅读 2.9k
2 个回答
✓ 已被采纳

找到了一个方案,主要依靠 div的。contenteditable="true"

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>自动变长输入框</title>
    <link rel="stylesheet" href="styles.css">
</head>
<style>
    .input-container {
        width: 200px;
    }
    .auto-expand {
        display: inline;
        word-break: break-all;
        word-wrap: break-word;
        border: 1px solid black;
    }
</style>
<body>
<div class="input-container">
    你好,
    <div class="auto-expand" contenteditable="true">111</div>
    请下午来开会
</div>
</body>
</html>

image.png

vue
import Vue from "vue";

export const autoTextarea = Vue.directive("autoTextarea", {
inserted: (el, binding) => {

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);
el.addEventListener("focus", change);
  el.addEventListener("blur", change);

},
});

//main.js

import { autoTextarea } from "./utils/input";
Vue.prototype.$autoTextarea = autoTextarea;

<template>
<div class="text">

 <textarea class="textarea" v-autoTextarea="{minHeight: 36}"></textarea>

</div>
</template>
<style scoped lang="scss">
.textarea {

width: 240px;
height: 36px;
line-height: 28px;
overflow: hidden;
resize: none;
outline-color: #ccc; // 鼠标聚焦边框颜色
border-color: #ccc;
border-radius: 5px;
padding-left: 6px;

}
.textarea:focus {//去除聚焦效果

outline: none;

}
</style>

//信息发送后输入框聚焦

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏