在Javascript中获取字符宽度 [英] Getting character width in Javascript
问题描述
我想得到一个字符的宽度,用于计算字符串内任何给定字符(以像素为单位)的位置。我认为这很容易,因为我使用的是等宽字体,但我遇到了问题。
I would like to get the width of a character for calculating the position of any given character (in pixels) inside a string. I figure this would be easy since I am using a monospace font but I have a problem.
我已经尝试了这个答案但这对大字符串不起作用。精度太差了,这意味着它可以工作,我可以得到字符串中前几个字符的位置但是之后,比方说10个字符,精度是如此之差,以至于我得到的字符距离实际上是远远的先给出角色的位置。
I have tried the suggestions in this answer but this doesn't work for large strings. The precision is too poor which means that it works and I can get the position of the first few characters in the string but after, say 10 characters, the precision is so bad that the position I get for the character is so far off it's actually giving the position of the character before.
我想做的是得到一个角色的宽度,这样我就可以这样写:
What I would like to do is get the width of a character so I can just write something like this:
var charWidth = ???;
var position = 5; // Shuold get the position of the fifth character in the string
var calculatedPosition = charWidth * position;
推荐答案
CSS:
.textDimensionCalculation {
position: absolute;
visibility: hidden;
height: auto;
width: auto;
white-space: nowrap;
}
JS:
var calculateWordDimensions = function(text, classes, escape) {
classes = classes || [];
if (escape === undefined) {
escape = true;
}
classes.push('textDimensionCalculation');
var div = document.createElement('div');
div.setAttribute('class', classes.join(' '));
if (escape) {
$(div).text(text);
} else {
div.innerHTML = text;
}
document.body.appendChild(div);
var dimensions = {
width : jQuery(div).outerWidth(),
height : jQuery(div).outerHeight()
};
div.parentNode.removeChild(div);
return dimensions;
};
在他的博客上,他写道
在这个小片段的帮助下,我们现在可以像这样计算文本
的尺寸。:
With the help of this little snippet we can now calculate the text dimensions like this.:
var dimensions = calculateWordDimensions('42 is the answer!'); <!--obviously a hitchhikers guide fan, lol --->
console.log(dimensions.width);
console.log(dimensions.height);
$.fn.textWidth = function(text, font) {
if (!$.fn.textWidth.fakeEl) $.fn.textWidth.fakeEl = $('<span>').hide().appendTo(document.body);
$.fn.textWidth.fakeEl.text(text || this.val() || this.text()).css('font', font || this.css('font'));
return $.fn.textWidth.fakeEl.width();
};
这篇关于在Javascript中获取字符宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!