在Firefox和Chrome中,Jquery .width()结果有所不同

时间:2013-04-12 14:01:56

标签: jquery google-chrome firefox width

我正在尝试测量字符串的宽度。为此,我创建一个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

0 个答案:

没有答案
相关问题