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

不過最後發現, 這個支持英文, 對中文好像不感冒. @_@

相关文章:

  • 2021-11-28
  • 2021-08-02
  • 2022-12-23
  • 2021-08-24
  • 2022-12-23
  • 2021-12-13
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-09-23
  • 2021-10-22
  • 2021-06-12
  • 2022-12-23
  • 2021-09-29
  • 2022-12-23
  • 2021-06-13
相关资源
相似解决方案