Getting character width in Javascript

和自甴很熟 提交于 2019-12-02 00:18:11

问题


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.

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;

回答1:


Try this solution, developed by Ben Ripkens

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;
};

On his blog he writes

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);

An alternate [jquery] solution has been written also by Phil Freo

$.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();
};


来源:https://stackoverflow.com/questions/43965616/getting-character-width-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!