input根据内容自适应宽度

input根据内容自适应宽度

最近在写自己个人网站时,发布文章功能需要一个添加标签组件。点击加号,输入文本。而这里的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属性

}

不理想的原因皆是:输入英文字符满足需求,输入中文字符则增加的宽度不固定

最后使用了h5的contenteditable属性很简单的解决了这个需要

class="my-input"

contenteditable="true"

>

// css

.my-input {

color: #66757f;

display: inline-block;

height: 22px;

min-width: 20px;

max-width: 100px;

}

效果展示

查看实例

https://blog.csdn.net/weixin_42565137/article/details/101286700


枇杷膏怎么做?配方都告诉你,再也不用花钱买了
无限暖暖服装店位置大全