最近做項目的時候需要得到所輸入的字符串的寬度, 想了很久, 也google也很久, 最後還是無解.
後來想想, 是否可以變通一下, 從別的地方取得它的寬度. 經過一番頭腦風暴.
終於得出瞭解決辦法:
<!--
//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>
<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>
不過最後發現, 這個支持英文, 對中文好像不感冒. @_@