如何查找字符串的物理长度? [英] How do I find the physical length of a string?

查看:110
本文介绍了如何查找字符串的物理长度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的网站中,用户的用户名始终显示在每个页面的顶部(以及网站标题,其他网页链接等),字体大小为3

In my website, the user's username is always displayed at the top of every page (along with the site title, other page links, etc.) in a font size of "3"

我花了很长时间才弄清楚这一点,但最终我注意到,用户名长的用户名结束了每个页面顶部的间距,所有的文本被推送下一行,使整个事情看起来像罪恶(它只有个人用户可见,因为它是他们的用户名,但我不想让我的用户看到它)。

It took me a really long time to figure this out, but it eventually came to my attention that the users with really long usernames ended up messing with the spacing at the top of every page and all the text gets pushed down a line, making the whole thing look ugly as sin (it's only visible to the individual user since it's their username, but I don't want any of my users seeing it at all).

我不是在问如何找到他们姓名中的字符数量 - 我想知道的是我如何确定他们的名字将占用的空间的物理量

I'm not asking how to find the number of characters in their name -- what I want to know is how I can determine the physical amount of space their name will take up and, in the event it will be too long, reduce the font size to 2, or even 1 if necessary.

为什么一个简单的strlen()不会出现这种情况呢?工作是因为潜在的空间差异(Tragic Dionysus比HERSHEYFEVER占用更少的空间,而不管前者有更多的字符)。

The reason why a simple strlen() wouldn't work is because of the potential space differences ("Tragic Dionysus" takes up less room than "HERSHEYFEVER", regardless that the former has more characters in it).

推荐答案

你不能使用PHP来实现这一点 - 因为这么多取决于前端样式(字体族,字体大小,字体样式等)。您可以使用jQuery来确定元素长度,并根据需要应用某些功能:

You cannot use PHP for this - because so much depends on front-end styling (font-families, font-size, font-styling, etc.). You can use jQuery to ascertain the element length, and apply certain functionality if needed:

HTML

<span id="box"><?=$yourString?></span> 

jQuery

$(function() {
   var box = $('#box');
   if (box.width() >= 50) {
      box.addClass('massiveLength');
   }
});

或者,如果您要对所有元素应用某项,这里是一个jsFiddle 如何显示。

Or, if you want to apply something to all elements, here's a jsFiddle showing you how.

这篇关于如何查找字符串的物理长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆