[英]How to get a pixel width from a span programmatically with jquery
I'm trying to do something like: 我正在尝试做类似的事情:
$('<span>random text in here</span>').width()
But the width it's returning is 0. (The reason I'm trying to do this is to get the pixel width of a given text.) 但它返回的宽度是0.(我试图这样做的原因是获取给定文本的像素宽度。)
How would I get this width, programmatically? 我如何以编程方式获得此宽度?
Thanks 谢谢
You have to have it rendered. 你必须让它呈现。
You may do this : 你可以这样做:
var s = $('<span>random text in here</span>');
s.appendTo(document.body);
var w = s.width();
s.remove();
Note that : 注意 :
Here's the solution measuring the width of some text using an in memory canvas : 这是使用内存画布测量某些文本宽度的解决方案:
var canvas = document.createElement('canvas');
var c = canvas.getContext('2d');
// set here c.font to adjust it to your need
var w = c.measureText('random text in here').width;
I would use the first one in the general case but it might depend on why you want to measure the text. 我会用在一般情况下,第一个,但它可能取决于你为什么要测量的文本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.