确定 Javascript/jQuery 中字符串的像素长度?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2057682/
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
Determine Pixel Length of String in Javascript/jQuery?
提问by GSto
Is there any way to determine the pixel length of a string in jQuery/JavaScript?
有没有办法确定 jQuery/JavaScript 中字符串的像素长度?
采纳答案by Natrium
Wrap text in a spanand use jquery width()
将文本包裹在一个跨度中并使用jquery width()
回答by élektra
The contexts used for HTML Canvases have a built in method for checking the size of a font. This method returns a TextMetricsobject, which has a width property which contains the width of the text.
用于 HTML Canvases 的上下文具有用于检查字体大小的内置方法。此方法返回一个TextMetrics对象,该对象具有包含文本宽度的 width 属性。
function getWidthOfText(txt, fontname, fontsize){
if(getWidthOfText.c === undefined){
getWidthOfText.c=document.createElement('canvas');
getWidthOfText.ctx=getWidthOfText.c.getContext('2d');
}
var fontspec = fontsize + ' ' + fontname;
if(getWidthOfText.ctx.font !== fontspec)
getWidthOfText.ctx.font = fontspec;
return getWidthOfText.ctx.measureText(txt).width;
}
Or, as some of the other users have suggested, you can wrap it in a spanelement:
或者,正如其他一些用户所建议的,您可以将其包装在一个span元素中:
function getWidthOfText(txt, fontname, fontsize){
if(getWidthOfText.e === undefined){
getWidthOfText.e = document.createElement('span');
getWidthOfText.e.style.display = "none";
document.body.appendChild(getWidthOfText.e);
}
if(getWidthOfText.e.style.fontSize !== fontsize)
getWidthOfText.e.style.fontSize = fontsize;
if(getWidthOfText.e.style.fontFamily !== fontname;
getWidthOfText.e.style.fontFamily = fontname;
getWidthOfText.e.innerText = txt;
return getWidthOfText.e.offsetWidth;
}
EDIT 2020: added font name+size caching at Igor Okorokov's suggestion.
编辑 2020:根据 Igor Okorokov 的建议添加了字体名称+大小缓存。
回答by Topher Fangio
I don't believe you can do just a string, but if you put the string inside of a <span>with the correct attributes (size, font-weight, etc); you should then be able to use jQuery to get the width of the span.
我不相信你可以只做一个字符串,但是如果你把字符串放在<span>具有正确属性(大小、字体粗细等)的 a 中;然后您应该能够使用 jQuery 来获取跨度的宽度。
<span id='string_span' style='font-weight: bold; font-size: 12'>Here is my string</span>
<script>
$('#string_span').width();
</script>
回答by Grinn
Put it in an absolutely-positioned div then use clientWidth to get the displayed width of the tag. You can even set the visibility to "hidden" to hide the div:
将其放在绝对定位的 div 中,然后使用 clientWidth 获取标签的显示宽度。您甚至可以将可见性设置为“隐藏”以隐藏 div:
<div id="text" style="position:absolute;visibility:hidden" >This is some text</div>
<input type="button" onclick="getWidth()" value="Go" />
<script type="text/javascript" >
function getWidth() {
var width = document.getElementById("text").clientWidth;
alert(" Width :"+ width);
}
</script>
回答by RJ Kelly
Based on vSync's answer, the pure javascript method is lightning fast for large amount of objects. Here is the Fiddle: https://jsfiddle.net/xeyq2d5r/8/
基于 vSync 的回答,纯 javascript 方法对于大量对象来说是闪电般的。这是小提琴:https: //jsfiddle.net/xeyq2d5r/8/
[1]: https://jsfiddle.net/xeyq2d5r/8/ "JSFiddle"
I received favorable tests for the 3rd method proposed, that uses the native javascript vs HTML Canvas
我收到了对提议的第三种方法的有利测试,该方法使用本机 javascript 与 HTML Canvas
Google was pretty competive for option 1 and 3, 2 bombed.
谷歌在选项 1 和 3、2 上的竞争非常激烈。
FireFox 48:
Method 1 took 938.895 milliseconds.
Method 2 took 1536.355 milliseconds.
Method 3 took 135.91499999999996 milliseconds.
FireFox 48:
方法 1 耗时 938.895 毫秒。
方法 2 花费了 1536.355 毫秒。
方法 3 花费了 135.91499999999996 毫秒。
Edge 11
Method 1 took 4895.262839793865 milliseconds.
Method 2 took 6746.622271896686 milliseconds.
Method 3 took 1020.0315412885484 milliseconds.
Edge 11 方法 1 耗时 4895.262839793865 毫秒。
方法 2 耗时 6746.622271896686 毫秒。
方法 3 耗时 1020.0315412885484 毫秒。
Google Chrome: 52
Method 1 took 336.4399999999998 milliseconds.
Method 2 took 2271.71 milliseconds.
Method 3 took 333.30499999999984 milliseconds.
谷歌浏览器:52
方法 1 耗时 336.4399999999998 毫秒。
方法 2 耗时 2271.71 毫秒。
方法 3 耗时 333.30499999999984 毫秒。
回答by Andrew Marais
First replicate the location and styling of the text and then use Jquery width() function. This will make the measurements accurate.For example you have css styling with a selector of:
首先复制文本的位置和样式,然后使用 Jquery width() 函数。这将使测量准确。例如,您有一个带有以下选择器的 css 样式:
.style-head span
{
//Some style set
}
You would need to do this with Jquery already included above this script:
您需要使用已包含在此脚本上方的 Jquery 来执行此操作:
var measuringSpan = document.createElement("span");
measuringSpan.innerText = 'text to measure';
measuringSpan.style.display = 'none'; /*so you don't show that you are measuring*/
$('.style-head')[0].appendChild(measuringSpan);
var theWidthYouWant = $(measuringSpan).width();
Needless to say
不用说
theWidthYouWant
你想要的宽度
will hold the pixel length. Then remove the created elements after you are done or you will get several if this is done a several times. Or add an ID to reference instead.
将保持像素长度。然后在完成后删除创建的元素,或者如果这样做多次,你会得到几个。或者添加一个 ID 来引用。
回答by Tim Erickson
If you use Snap.svg, the following works:
如果您使用 Snap.svg,则以下内容有效:
var tPaper = Snap(300, 300);
var tLabelText = tPaper.text(100, 100, "label text");
var tWidth = tLabelText.getBBox().width; // the width of the text in pixels.
tLabelText.attr({ x : 150 - (tWidth/2)}); // now it's centered in x

