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
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.