如何取得輸入字符串的寬度

最近做項目的時候需要得到所輸入的字符串的寬度, 想了很久, 也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 (不自動換行)纔行.

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