【问题标题】:Getting character width in Javascript在Javascript中获取字符宽度
【发布时间】:2017-05-14 15:20:48
【问题描述】:

我想获取一个字符的宽度,以计算字符串中任何给定字符(以像素为单位)的位置。我认为这很容易,因为我使用的是等宽字体,但我遇到了问题。

我已经尝试过this answer 中的建议,但这不适用于大字符串。精度太差,这意味着它可以工作,我可以得到字符串中前几个字符的位置,但是在 10 个字符之后,精度太差了,以至于我得到的字符位置离它实际上太远了给出之前角色的位置。

我想做的是得到一个字符的宽度,这样我就可以写这样的东西:

var charWidth = ???;
var position = 5; // Shuold get the position of the fifth character in the string
var calculatedPosition = charWidth * position;

【问题讨论】:

  • 无法提出解决方案,因为我不完全清楚您要做什么 - 目标是根据字符串中字符的位置定位 HTML 元素吗?或者在字符串的那个点插入一些东西?
  • @Toby 我正在尝试在该位置放置另一个元素,是的。
  • @RachelGallen 链接问题的答案,我将创建一个带有字符串的隐藏 div,然后我用它来计算字符宽度。
  • 我正在努力,但这是您遇到的问题吗?看起来这里字符的宽度是9.6px(根据chrome中的开发工具),但clientWidth返回10px。所以它是准确的,但确实会因较长的字符串而崩溃。 codepen.io/mcoker/pen/ybEyrL
  • 你为什么不直接使用.childNodes()?它是准确的,因为它不关心宽度、字体或字符,它只关心节点(例如元素、文本等......)

标签: javascript html css text monospace


【解决方案1】:

试试这个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;
};

他在博客上写道

借助这个小 sn-p 我们现在可以计算文本 像这样的尺寸。:

var dimensions = calculateWordDimensions('42 is the answer!'); <!--obviously a hitchhikers guide fan, lol --->

console.log(dimensions.width);
console.log(dimensions.height);

alternate [jquery] solution 也由 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();
};

【讨论】:

  • 显然您不必将尺寸写入控制台.. 将它们用于您需要的任何计算.. 但我认为他的评论很有趣! :)
  • 谢谢!我试过了,它似乎工作得很好!非常感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-14
  • 2013-05-04
  • 2012-03-06
  • 2013-05-12
  • 2013-06-19
  • 2011-04-07
相关资源
最近更新 更多