Javascript:在预容器中获取文本字符串的显示宽度

Javascript : getting the display width of text string in a pre container, in em

本文关键字:字符串 取文本 显示 获取 Javascript      更新时间:2023-09-26

在容器中添加非等宽字体、制表符等…

那么如何派生一个文本字符串的宽度显示在容器中…

这在经常改变字体的设备/网站上很有用。因此,不需要在每次调整尺寸时"重新绘制"尺寸(使用插入、测量、删除)方法。其中一些没有事件可以触发/观察。

手动使用em工作到目前为止…问题是如何使之自动化。jQuery.width()返回px.

您可以将px转换为em。记住公式:

var em = px / fontSize;

所以,如果你有一个pre元素,font-size设置为1em,通常是16px,你在px中的宽度是800px,那么你在em中的宽度是800 / 1650em。希望这对你有所帮助。如果你觉得我的答案有用,就给我投票。

不完美,但可以完成工作(某种程度上)[使用jQuery]

// [div] : a dom node to test insertion of string (inherits its css prop too)
// [str] : the string to test against
function getEmLen( div, str ) {
    var oriInner = div.innerHTML;
    var res;
    div.innerHTML = '<a>'+str+'</a><a>m</a>';
    res = Math.ceil( 100 * (jQuery(div.firstChild).width()) / (jQuery(div.lastChild).width()) ) / 100; 
    //the * 100, / 100 is to remove long trailing divides
    div.innerHTML = oriInner;
    return ''+res+'em';
}