我有一个输入字段和maxLength值,我想将输入字段分为相等的maxLength虚拟框,以便每个框包含一个字母。
例如,如果我的maxLength值为10并且输入宽度为100px,我想将这10个字符分布在整个输入宽度上,则期望的结果如下所示
我决定使用下面的代码并添加css letterSpacing属性,根据字符W(因为它是最宽的字符)来计算字母间距,但这并不能提供准确的结果
enter code here
function calculateLetterSpacing(fontInfo, width, maxLength) {
const inputWidth = width;
const span = document.createElement('span');
span.innerText = "W";
span.style.fontSize = fontInfo.fontSize;
span.style.fontFamily = fontInfo.fontName;
document.body.appendChild(span);
const charMaxWidth = span.offsetWidth;
return (inputWidth - charMaxWidth*maxLength)/maxLength;
}
Run Code Online (Sandbox Code Playgroud)
是否有任何直接的CSS属性可以让我做到这一点。
PS字体可以是任何东西,不是等宽的。