简体   繁体   English

如何使用jquery以编程方式从跨度获取像素宽度

[英]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();

Demonstration 示范

Note that : 注意 :

  • nothing is displayed if you do this like I do in one go. 如果你像我一口气这样做,就不会显示任何内容。 For all practical purposes, nothing is inserted in the DOM, 出于所有实际目的,DOM中没有插入任何内容,
  • you could also use an in memory canvas but it wouldn't handle anything more complex than simple text and wouldn't take into account your span's css settings. 你也可以使用内存画布,但它不会处理比简单文本更复杂的东西,也不会考虑你的span的css设置。

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;

Demonstration 示范

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM