使用 JavaScript 获取以像素为单位的字符串长度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14852925/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 18:09:05  来源:igfitidea点击:

Get string length in pixels using JavaScript

javascriptstringpixelsstring-length

提问by Kundan Atre

I want to know exact length in pixels of String i.e. "Hello World".

我想知道字符串的确切长度(以像素为单位),即“Hello World”。

It should not be length of my container.

它不应该是我的容器的长度。

Any Help???

任何帮助???

回答by Mike

Put your text in a <span>and use JavaScript to measure the width of your <span>.

将您的文本放在 a 中<span>并使用 JavaScript 来测量您的<span>.

HTML:

HTML:

<span id="text">Dummy text</span>

JavaScript:

JavaScript:

var textWidth = document.getElementById("text").clientWidth;

jQuery:

jQuery:

$('#text').width();

回答by Artem Sobolev

You can create some inline element (span, for example), set your string as element's content (innerHTML), insert it into document (append to some element) and get it's width (clientWidth).

您可以创建一些内联元素(span例如),将字符串设置为元素的内容(innerHTML),将其插入文档(附加到某个元素)并获取其宽度(clientWidth)。

There is no other way to measure length of string in pixels because it depends on font style.

没有其他方法可以以像素为单位测量字符串的长度,因为它取决于字体样式。

回答by user2068219

Since the pixel length of the string will change depending on independently applied CSS attributes such as font and weight and size, I can't see this being possible in JS.

由于字符串的像素长度会根据独立应用的 CSS 属性(例如字体、粗细和大小)而变化,因此我认为这在 JS 中是不可能的。