在给定动态宽度(例如,宽度 = 100%)的情况下,JavaScript 有没有办法获得可以在输入字段上显示的最大字符数?
例如,如果输入字段的值为“123456789”,由于宽度限制,只有“1234567”可显示/可见,可显示字符的最大数量为“7”。
示例布局:
----------
|01234567|
----------
当前代码:(我遇到了不同字体样式的问题。另外,尚未考虑字体间距。getFontSize 的代码来自这里。)
function countLetters()
{
var inputLong = document.getElementById('inputLong');
var fontSize = getFontSize(inputLong);
var fieldWidth = getWidth(inputLong);
console.log('Number of Visible Characters: ' + (fieldWidth / fontSize) );
}
function getFontSize(parentElement)
{
return Number(getComputedStyle(parentElement, "").fontSize.match(/(\d*(\.\d*)?)px/)[1]);
}
function getWidth(parentElement)
{
return parentElement.offsetWidth;
}