我正在尝试测量字符串的宽度。为此,我将字符串作为值创建一个 div 宽度,将其添加到 DOM 并使用 Jquery 的 .width() 测量宽度。
问题是当我在 Firefox 和 Chrome 中执行脚本时得到不同的结果。
我创建了一个 jsFiddle:http: //jsfiddle.net/7wjeB/2/
HTML:
<body>
<div>
<input id="input" value="office worker" style="display:block; position:static; font-family: Arial, Helvetica, sans-serif; font-size: 25px;"></input>
<button onclick="calc()" style="font:Arial; font-size:12px;">Calculate width</button>
</div>
</body>
JavaScript:
width = function(font, string) {
var f = font || '12px arial', o = $('<div>' + string + '</div>').css({
'position' : 'absolute',
'float' : 'left',
'white-space' : 'nowrap',
'visibility' : 'hidden',
'font' : f
}).appendTo($('body')), w = o.width();
o.remove();
return w;
};
calc = function() {
var content = $("#input").val();
var font = $("#input").css("font-size") + " " + $("#input").css("font-family");
alert(width(font, content));
};
我正在使用 Firefox 版本 19.0.2 和 Chrome 版本 26.0.1410.64