input输入框固定前置内容,前置内容长度不固定且不可删除

在输入框前添加前置内容,内容不固定且不可删除,前置内容之后可继续输入,如下所示

1.获取输入框,根据前置内容的长度控制缩进距离

  mounted() {
    let frontMsg = "我是前置内容";
    const el = document.querySelector('.myInput')
    el.setAttribute('data-content', frontMsg)
    const textArea = document.querySelector('.myInput .el-input__inner')
    const textWidth = this.getTextWidth(frontMsg,textArea)
    textArea.style.padding = '0'
    textArea.style.textIndent =textWidth + 4 + 'px'
  },


2.根据前置内容的长度计算它的宽度

getTextWidth(text, element){
      const canvas = document.createElement('canvas');
      const context = canvas.getContext('2d');
      context.font = getComputedStyle(element).font;
      return context.measureText(text).width;
    },

3.设置样式

 .myInput::before{
   content: attr(data-content); 
   height: 35px;
   line-height: 35px;
   display: block;
   position: absolute;
   left: 2px;
   top: 3px;
   font-size: 14px;
   color: red;
  }

完整代码

<template>
<div class="box">
  <el-input class="myInput" type="text" v-model="message"></el-input>
</div>
</template>

<script>
export default {
  name: "index",
  data(){
    return {
      message:''
    }
  },
  mounted() {
    let frontMsg = "我是前置内容";
    const el = document.querySelector('.myInput')
    el.setAttribute('data-content', frontMsg)
    const textArea = document.querySelector('.myInput .el-input__inner')
    const textWidth = this.getTextWidth(frontMsg,textArea)
    textArea.style.padding = '0'
    textArea.style.textIndent =textWidth + 4 + 'px'
  },
  methods:{
    getTextWidth(text, element){
      const canvas = document.createElement('canvas');
      const context = canvas.getContext('2d');
      context.font = getComputedStyle(element).font;
      return context.measureText(text).width;
    },
  },
}
</script>

<style lang="less" scoped>
.box {
  display: flex;
  justify-content: center;
  .myInput {
    width: 600px;
    height: 35px;
    font-size: 14px;
  }
 .myInput::before{
   content: attr(data-content);
   height: 35px;
   line-height: 35px;
   display: block;
   position: absolute;
   left: 2px;
   top: 3px;
   font-size: 14px;
   color: red;
  }
}


</style>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值