请检查一下。是使用画布的解决方案
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());演示使用
编辑
使用画布的解决方案不是最好的,每个浏览器处理不同的画布大小。
这是一个使用临时元素获取文本大小的好方法。
演示版
编辑
canvas规范没有提供用于测量字符串高度的方法,因此可以使用
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']);


