admin管理员组文章数量:1315811
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.)
How would I get this width, programmatically?
Thanks
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.)
How would I get this width, programmatically?
Thanks
Share Improve this question edited Mar 4, 2017 at 10:20 Shai UI asked Nov 7, 2012 at 16:24 Shai UIShai UI 52k77 gold badges217 silver badges316 bronze badges 1-
2
The width is
0
because the span has no size. It has not been added to the DOM. Where it lies in the DOM will change its font-size, and is therefore impossible to calculate without rendering it in some way. – zzzzBov Commented Nov 7, 2012 at 16:26
1 Answer
Reset to default 11You 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,
- you could also use an in memory canvas but it wouldn't handle anything more plex than simple text and wouldn't take into account your span's css settings.
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.
本文标签: javascriptHow to get a pixel width from a span programmatically with jqueryStack Overflow
版权声明:本文标题:javascript - How to get a pixel width from a span programmatically with jquery - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741988772a2408841.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论