输入内容后,输入框宽度根据内容自动撑开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>