惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

S
Secure Thoughts
Security Latest
Security Latest
Simon Willison's Weblog
Simon Willison's Weblog
O
OpenAI News
GbyAI
GbyAI
L
LINUX DO - 最新话题
A
Arctic Wolf
T
Tor Project blog
G
GRAHAM CLULEY
I
InfoQ
博客园_首页
IT之家
IT之家
The Register - Security
The Register - Security
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
P
Proofpoint News Feed
The GitHub Blog
The GitHub Blog
Blog — PlanetScale
Blog — PlanetScale
N
Netflix TechBlog - Medium
K
Kaspersky official blog
博客园 - 三生石上(FineUI控件)
S
SegmentFault 最新的问题
U
Unit 42
PCI Perspectives
PCI Perspectives
量子位
P
Palo Alto Networks Blog
S
Securelist
T
Troy Hunt's Blog
博客园 - 【当耐特】
Recorded Future
Recorded Future
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
S
Security Affairs
Engineering at Meta
Engineering at Meta
T
The Blog of Author Tim Ferriss
博客园 - 聂微东
罗磊的独立博客
N
News and Events Feed by Topic
人人都是产品经理
人人都是产品经理
B
Blog RSS Feed
NISL@THU
NISL@THU
C
Cisco Blogs
T
Threatpost
有赞技术团队
有赞技术团队
Forbes - Security
Forbes - Security
Hugging Face - Blog
Hugging Face - Blog
Last Week in AI
Last Week in AI
T
The Exploit Database - CXSecurity.com
Cloudbric
Cloudbric
Cyberwarzone
Cyberwarzone
Google DeepMind News
Google DeepMind News
C
Cyber Attacks, Cyber Crime and Cyber Security

博客园 - Leonny

IIS站点/虚拟目录中访问共享目录(UNC)以及建立后的应用程序的信任级别问题 谁说用Azure就一定要Vista/Win7?Window2003/xp下安装 Windows Azure Tools for Microsoft Visual Studio IE的window.showModalDialog出现内存不足的问题 - Leonny - 博客园 关于清理JBoss服务器端jsp文件缓存的问题 提取assemblyinfo.cs文件里的guid值 经常坐电脑旁的人必喝的健康饮品 Firefox图片模糊的问题 MS SQL Server2005如何得到记录的行号 [原创]OWC生成Excel的效能优化 [译]NUnitForms官方说明文档 C#取得MS Word的总页数 VS2008中文版安装ASP.NET MVC Beta WinForm下ComboBox添加项与设定预选项 成功申请了GAE Vista删你文件没商量 3大数据库的变量参数符号 新立得软件包管理器出错 Repeater中點擊按鈕事件時要注意頁面PostBack的問題 關於Web Service 中使用NHibernate時無法序列化IList的問題
如何取得輸入字符串的寬度
Leonny · 2007-09-07 · via 博客园 - Leonny

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

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