input宽度根据内容自适应几种尝试

2,236 阅读1分钟

input宽度根据内容自适应。百度大多是这两种方法,结果都不是很理想。 // 方法一

   <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属性

  }

不理想的原因:输入英文字符满足需求,输入中文字符则增加的宽度不固定,在安卓、ios手机的显示也有差异。

// 方法三

使用了h5的contenteditable属性很简单的解决了这个需要, 输入后生效,且小程序支持性不好。

    class="my-input"

    contenteditable="true"

// css

.my-input {

      color: #66757f;

      display: inline-block;

      height: 22px;

      min-width: 20px;

      max-width: 100px;

      }

// 方法四

1、用 div 嵌套 input 和 label 

2、将 input 输入的内容同步到 label 中,并将 label 设置成不可见

3、将 input 盖在 label 上

html代码

<div class="input-box">
        <input type="text" id="input-label" class="input-box__input" :value="valLabel" @input="changeWidthLabel">
        <label for="" id="label" class="input-box__label" v-text="valLabel"></label>
      </div>

css部分需要需要注意 input 和 label 的font-family和font-size必须一致

/* css 代码 */

.input-box {

display: inline-flex;

align-items: center;

box-sizing: border-box;

position: relative;

border: 1px solid #000;

border-radius: 5px;

height: 40px;

min-width: 50px;

/* font family is very important */

font-family: Arial,'microsoft yahei';

font-size: 14px;

}

.input-box__label {

display: inline-block;

font-size: inherit;

line-height: normal;

visibility: hidden;

font-family: inherit;

padding: 0 10px;

}

.input-box__input {

box-sizing: border-box;

position: absolute;

display: inline;

font-size: inherit;

font-family: inherit;

line-height: normal;

border-radius: inherit;

height: 100%;

width: 100%;

outline: 0;

border: 0;

margin: 0;

padding: 0 10px;

} 这种方式应该没有兼容性问题,具体样式ui大家可以做微调,有更好的实现方式可相互分享。