html设置input宽度由内容决定,CSS实现input宽度根据输⼊内
容⾃适应
input 宽度根据输⼊的内容⾃适应的应⽤场景不是很常见,但不排除有特殊需求的情况,例如⾦额输⼊框⼀般都希望能完整的看到所输⼊的⾦额。
常规的⽅案是通过JS获取输⼊的⽂本长度后乘以⽂本的宽度,但中英⽂的⽂本宽度不相同,所以通过此类⽅式实现的效果不太理想。
还有⼀种⽤html的contenteditable属性来模拟input的⽅案,这种⽅案在web中确实可⾏,但是⽆法兼容各⼩程序。
CSS实现该效果的原理:
1、⽤div嵌套“input”和“label”
2、将“input”输⼊的内容同步到“label”中,并将“label”设置成不可见
3、将“input”盖在“label”上
看完以上步骤,聪明的你是不是已经猜到实现细节了呢~
其实是⽤“label”来撑开⽗容器的宽度,再让“input”的宽度⾃适应⽗容器的宽度即可。
具体实现代码:
css部分需要需要注意“input”和“label”的font-family和font-size必须⼀致
.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: Arial,'microsoft yahei';
borderboxfont-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;
}
这⾥⽤到了JS将“input”输⼊的内容同步到“label”中,如果使⽤mvvm架构框架即可省去这⼀步。document.querySelector('#input').addEventListener('input', (e) => {
document.querySelector('#label').innerHTML = e.target.value;
})
效果预览:⾛你~

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。