如何取得输入字符串的宽度

最近做项目的时候需要得到所输入的字符串的宽度, 想了很久, 也google也很久, 最后还是无解.
后来想想, 是否可以变通一下, 从别的地方取得它的宽度. 经过一番头脑风暴.
终于得出了解决办法:

<script language="javascript" type="text/javascript">
<!--
//int : 取得输入字符串的宽度
function getStrWidth(str)
{
    
var w = 0;
    
var id = 'check_new_line_span_leonny';
    
var s = document.getElementById(id);
    s.innerHTML 
= str;
    s.style.display 
= '';
    w 
= s.scrollWidth;
    s.style.display 
= 'none';
    
return w;
}
//-->
</script>

<input type="text" id="text1" name="text1" value="" style="font-size:12px;font-family:'Palatino linotype';" />
<br />
<input type="button" value="Get Text Width" onclick="alert(getStrWidth(document.getElementById('text1').value));" />
<br />
<span id="check_new_line_span_leonny" style="font-size:12px;font-family:'Palatino linotype';white-space:nowrap;"></span>
这里有一个要注意的地方, 就是textbox的字体大小和字体要与span的一致.而且span必需设置while-space: nowrap (不自动换行)才行.

不过最后发现, 这个支持英文, 对中文好像不感冒. @_@
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章