请检查这个。是使用画布的解决方案
function get_tex_width(txt, font) {
this.element = document.createElement('canvas');
this.context = this.element.getContext("2d");
this.context.font = font;
return this.context.measureText(txt).width;
}
alert('Calculated width ' + get_tex_width("Hello World", "30px Arial"));
alert("Span text width "+$("span").width());
演示使用
编辑
使用画布的解决方案并不是最好的,每个浏览器处理不同的画布大小。
这是使用临时元素获取文本大小的一个很好的解决方案。
演示
编辑
画布规范没有给我们测量字符串高度的方法,因此我们可以使用parseInt(context.font)
. 获取宽度和高度。此技巧仅适用于 px 大小。
function get_tex_size(txt, font) {
this.element = document.createElement('canvas');
this.context = this.element.getContext("2d");
this.context.font = font;
var tsize = {'width':this.context.measureText(txt).width, 'height':parseInt(this.context.font)};
return tsize;
}
var tsize = get_tex_size("Hello World", "30px Arial");
alert('Calculated width ' + tsize['width'] + '; Calculated height ' + tsize['height']);