2

在给定动态宽度(例如,宽度 = 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;
}
4

2 回答 2

3

这取决于很多参数:使用的字体、字体大小、字母间距……要知道确定的大小可以容纳多少个字符并不简单……

你可以避免这些并说“好的,一个字母是 8px 宽(平均)所以长度是myInput.value.length * 8。或者你可以设置一个等宽字体,每个字母都有相同的宽度。

于 2013-08-05T08:49:51.527 回答
2

正如Maxime Lorant所说,它取决于很多参数。如果您想获得近似尺寸,请尝试以下操作:

修改的

<style type='text/css'>
#your_input{
    font-family:font-family:"Times New Roman",Georgia,Serif;
    font-size:12px;
    letter-spacing:0px;
}
#ruler{
    font-family:font-family:"Times New Roman",Georgia,Serif;    
    font-size:12px;
    letter-spacing:0px;
    position: absolute;
    visibility: hidden;
    height: auto;
    width: auto;
}
</style>
<script language="javascript">
    function calLen() {
        // calculate the approximate length of characters
        var input_width = document.getElementById('your_input').offsetWidth;
        var ruler_width = document.getElementById('ruler').offsetWidth;
        var ruler_text = document.getElementById('ruler').innerHTML;
        var ruler_len = ruler_text.length;
        var input_len = parseInt((input_width/ruler_width)*ruler_len,10);
        alert("approximate length is " + input_len);
    }
</script>

<body>
    <input type="text" id="your_input" value="">
    <div id="ruler">0123456789abcdefghijklmnopqrstuvwxyz</div>
    <a href="javascript:calLen()">calLen</a>
</body>
于 2013-08-05T09:17:30.510 回答