jquery中查找文本宽度
我正在尝试计算文本宽度(以 px 为单位)。
我将从html中取出一个字符串,这个字符串也可能包含一些特殊字符(在这个例子中只是一个连字符),并将这个字符串作为div的html内容,并计算字符串宽度。
但我得到了奇怪的结果。
如果有更好的方法来获取文本宽度,跨浏览器!,请告诉我。
我做了一个小提琴:
谢谢!
I am trying to to calculate text width in px.
I will take a string from html, this string may contain some special characters as well (in this example just a hyphen), and make this string an html content of a div, and calculate string width.
But I am getting strange results.
If there is an better way to get text width, cross-browser!, please let me know.
I have made a fiddle:
Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
#holder
添加float: left;
#holder
为宽度测试容器,默认为width: auto;< /代码>。换句话说,它覆盖了 100% 的浏览器窗口,并为您提供混合的结果。
如果
#holder
超过了容器的宽度,您可以考虑将white-space: nowrap;
添加到其中。更新了小提琴
Add
float: left;
to#holder
#holder
which is the test container for width, is defaulting towidth: auto;
. In other words, it is spanning 100% of the browser window and giving you the mixed results.You might consider adding
white-space: nowrap;
as well to#holder
should it ever exceed the width of it's container.Updated fiddle
元素设置为跨越其父元素的宽度,因此更改字体大小不会影响其实际宽度。将您的
更改为
应该可以满足您的需求。
<div>
elements are set to span the width of their parent element, so changing the font size will have no effect on its actual width. Changing your<div>
to a<span>
should give you what you're looking for.它可能看起来很恶心,但给了你宽度:
http://jsfiddle.net/adaz/YaPcP/43/
It may look nasty but gives you the width:
http://jsfiddle.net/adaz/YaPcP/43/