在输入框前添加前置内容,内容不固定且不可删除,前置内容之后可继续输入,如下所示
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>