search

Home  >  Q&A  >  body text

How to calculate string width?

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梦2717 days ago886

reply all(3)I'll reply

  • 黄舟

    黄舟2017-06-17 09:18:56

    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

    reply
    0
  • 欧阳克

    欧阳克2017-06-17 09:18:56

    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.

    reply
    0
  • 三叔

    三叔2017-06-17 09:18:56

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

    reply
    0
  • Cancelreply