输入内容后,输入框宽度根据内容自动撑开contenteditable=“true“

输入内容后,输入框宽度根据内容自动撑开contenteditable=“true“

产品需求:输入内容后,输入框宽度根据内容自动撑开
前端实现思路
1.使用element-ui 的el-input宽度设置auto (不可行)
2.使用input输入框宽度设置 auto (不可行)
实在想不到怎么做了,终极大招:百度一下,结果还真找到了方法使用 contenteditable=“true” 这个属性即可,但是百度找到的方法只能输入内容后宽度自动变宽,这个需求还不够用,我自己还得加入清空方法clear 不需要内容的时候把内容清空掉(下方代码cv即食)

在这里插入图片描述

<template>
  <div>
    <div class="mockinput">
      <div
        ref="input"
        class="input"
        contenteditable="true"
        tabindex="1"
        placeholder="请输入"
        @keydown="textareaKeydown($event)"
        @input="inputfn($event)"
      ></div>
      <span class="clear" @click="clear" v-if="inputValue">×</span>
    </div>
    <div>结果:{{ inputValue }}</div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      inputValue: "",
    };
  },
  mounted() {},
  watch: {},
  methods: {
    clear() {
      console.log("xx");
      this.inputValue = "";
      document.querySelector(".input").innerText = "";
    },
    inputfn(event) {
      this.inputValue = event.target.innerText;
    },
    //监听按键操作
    textareaKeydown(event) {
      if (event.keyCode === 13) {
        event.preventDefault(); // 阻止浏览器默认换行操作
        return false;
      }
    },
  },
};
</script>
<style lang="less" scope>
.input {
  min-width: 80px;
  max-width: 180px;
  overflow: hidden;
  white-space: nowrap;
  display: inline-block;
  height: 30px;
  line-height: 30px;
  border-radius: 4px;
  border: 1px solid #ccc;
  padding: 2px 16px 2px 8px;
  pointer-events: none;
  vertical-align: middle;
  position: relative;
}
.mockinput {
  display: inline-block;
  position: relative;
  cursor: text;
}
.clear {
  cursor: pointer;
  position: absolute;
  right: -10px;
  top: 50%;
  transform: translateY(-50%);
}
</style>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

前端酱紫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值