How to calculate string width?
过去多啦不再A梦
过去多啦不再A梦 2017-06-17 09:16:56
0
3
912

for example

var str = '你好,world'.

is placed in p, and p is a 12px font. Other conditions are not considered. So what is the width of str?

If they are all Chinese characters, then it is okay to write 8em. There can be Chinese characters and symbols in it. How to deal with it in js?

过去多啦不再A梦
过去多啦不再A梦

reply all(3)
黄舟

This cannot be calculated. The width is not only related to the font size, but also the font, spacing, etc. It's best to talk about your intentions. I think you are thinking in the wrong direction

学霸

Using canvas’s measureText() API, you can calculate it and achieve your effect. However, it is obvious that adding it to the canvas for calculation would be redundant and unnecessary.
//Maybe, if you add spacing, it would be really difficult.

三叔

I have a plan, it should work.
Set p to inline,
https://jsfiddle.net/afqkt0d1/1/

The content width of a non-replaceable inline element box is (the content width of) the content rendered inside it (before the relative offset of all children)
http://www.ayqy.net/doc/css2-. ..

It is also possible to set p to float, absolute, or fixed positioning, which is equivalent to giving p the wrapping property.

In another way, wrapping means making elements inline-block. For example, the default width of a p tag is 100% displayed, but once it is wrapped by the absolute attribute, the 100% default width will become the width of the adaptive internal element.

http://www.zhangxinxu.com/wor...

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template