In a recent write their own personal website, publish articles function need to add a label component. Click the plus sign, enter text. Here the input adaptation according to the width of the content requires. Most Baidu search these two methods, the results are not very satisfactory.
// 方法一
<input type="text" @input="changeWidth" id="myInput" class="my-input" />
changeWidth(e) {
let input = document.getElementById("myInput");
const l = input.value.length;
input.style.width = (l+1) * 15 + "px";
}
// 方法二
changeWidth(e) {
let input = document.getElementById("myInput");
input.size = input.value.length > 4 ? input.value.length : 4; // 这里input需要给个size属性
}
Are all reasons for the unsatisfactory: enter English characters meet demand, increased input Chinese characters is not fixed width
finally used h5 of the contenteditable attribute very simple solution to this need
<div
class="my-input"
contenteditable="true"
></div>
// css
.my-input {
color: #66757f;
display: inline-block;
height: 22px;
min-width: 20px;
max-width: 100px;
}
Show results
View examples
https://blog.csdn.net/weixin_42565137/article/details/101286700