Get string length in pixels with JavaScript

后端 未结 2 1404
离开以前
离开以前 2021-01-13 17:45

Let\'s say I have the string \"Hello\". This string is obviously five characters in length, but what is its length in pixels? Is there an easy way to determine this length i

相关标签:
2条回答
  • 2021-01-13 18:08

    You can determine the number of pixels the container of the string. You can do this by creating a hidden element in the DOM, setting the inner HTML to the string and then asking for the width.

    0 讨论(0)
  • 2021-01-13 18:30

    I don't think their is a good, easy way to do that, except computing the length of a container. The width depends on the font-size, the font, the letter-spacing, it will be different depending on the browser etc...

    0 讨论(0)
提交回复
热议问题