使用JavaScript获取以像素为单位的字符串长度 [英] Get string length in pixels with JavaScript

查看:121
本文介绍了使用JavaScript获取以像素为单位的字符串长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有字符串"Hello".该字符串的长度显然为五个字符,但以像素为单位的长度是多少?有没有一种简单的方法可以确定JavaScript中的长度?我想到了一个解决方案,其中必须向用户显示一个额外的div,但是这种方式似乎很麻烦而且很复杂.

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 in JavaScript? I have thought of a solution where an extra div would have to be displayed to the user, but this way seems hacky and complicated.

从更大的角度看,我试图确定填充该字符串长度需要多少个空格.正如您可能从上面说的那样,我认为最好的选择是从用户的角度简单地测量字符串的长度和单个空格字符,然后基于此来计算应替换多少个空格.顺便说一下,这将显示为HTML输入文本.

In the bigger picture, I am trying to determine how many spaces would be necessary to fill that length of the string. As you can probably tell from above, I think the best option would be to simply measure the length of the string and a single space character from the user's perspective and calculate how many spaces should replace the text based off of that. This is going to be displayed in an HTML input text, by the way.

谢谢.

推荐答案

您可以确定字符串容器的像素数.为此,您可以在DOM中创建一个隐藏元素,将内部HTML设置为字符串,然后要求宽度.

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.

这篇关于使用JavaScript获取以像素为单位的字符串长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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