jquery中查找文本宽度

发布于 2025-01-08 00:47:01 字数 299 浏览 4 评论 0原文

我正在尝试计算文本宽度(以 px 为单位)。

我将从html中取出一个字符串,这个字符串也可能包含一些特殊字符(在这个例子中只是一个连字符),并将这个字符串作为div的html内容,并计算字符串宽度。

但我得到了奇怪的结果。

如果有更好的方法来获取文本宽度,跨浏览器!,请告诉我。

我做了一个小提琴:

http://jsfiddle.net/YaPcP/39/

谢谢!

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:

http://jsfiddle.net/YaPcP/39/

Thank you!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

梦里南柯 2025-01-15 00:47:01

#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 to width: 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

她比我温柔 2025-01-15 00:47:01

元素设置为跨越其父元素的宽度,因此更改字体大小不会影响其实际宽度。将您的

更改为 应该可以满足您的需求。

<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.

ヤ经典坏疍 2025-01-15 00:47:01

它可能看起来很恶心,但给了你宽度:

http://jsfiddle.net/adaz/YaPcP/43/

It may look nasty but gives you the width:

http://jsfiddle.net/adaz/YaPcP/43/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文