简体   繁体   中英

How do I find the physical length of a string?

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.

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

An extensive Google search continually leaves me with more character counting methods, so I'm left clueless.

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');
   }
});

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

It is fundamentally impossible to do this well on the server.

Instead, use Javascript to get the actual width of the element, then reduce its font size.

我只是要抛弃它,但如果你将一个用户名块包装在一个元素中并给它一个最大宽度,它可能会解决你的问题。

<span style="max-width: 50px; overflow: hidden;">The Username Goes Here</span>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM