Monospace字体字符串宽度

时间:2014-04-25 16:52:00

标签: javascript html css width monospace

我有一个输入元素,它输入一个列表元素,两者都使用相同的等宽字体。 char_width_testspan元素的ID,其中包含1个具有相同等宽字体的字符。我检查这个宽度和 乘以输入字段中给定的字符串长度,以计算从该字符串创建的列表项的宽度。

var ul = document.getElementById('posts_list');
var li = document.createElement('li');
var txt = document.createTextNode(str);
ul.appendChild(li);
li.innerHTML = str;

li.style.width = (($("#char_width_test").width() * str.length)) + 'px';

上面的代码产生的宽度越多,空格越多,字符串越长。似乎有一些影响我失去的宽度的变量?

1 个答案:

答案 0 :(得分:1)

字符之间存在字距,因此一个字符的宽度不是你想要的倍数。

http://en.wikipedia.org/wiki/Kerning

确定一个字母的宽度和字距调整后,您需要n * char_width + (n - 1) * kerning_width更准确。

如果跨度上没有填充或边距,我可能会尝试类似kerning = width_of_two_characters - (width_of_one_character * 2)的内容。看看它是如何运作的。

相关问题