在服务器端计算文本宽度(以像素为单位)

dim*_*sch 5 node.js meteor

我正在尝试在我的服务器上使用以下代码来估计某些文本字段的长度,并可能在通过电子邮件发送之前修剪它们......

String.prototype.visualLength = function()
{
    var element = document.createElement("span");
    element.css({
        "visibility": "hidden",
        "white-space": "nowrap",
        "font-weight": "normal",
        "font-size": "18px",
        "line-height": "40px",
        "font-family": "Helvetica, Arial, sans-serif",
        "text-decoration": "none"
    });
    document.body.appendChild(element);
    element.innerHTML = this;
    return element.offsetWidth;
};

String.prototype.trimToPx = function(length)
{
    var tmp = this;
    var trimmed = this;
    if (tmp.visualLength() > length)
    {
        trimmed += "...";
        while (trimmed.visualLength() > length)
        {
            tmp = tmp.substring(0, tmp.length-1);
            trimmed = tmp + "...";
        }
    };
    return trimmed;
};
Run Code Online (Sandbox Code Playgroud)

显然我收到了一个错误,因为“文档”没有在服务器端定义。我添加了 Meteor 包htmljsdomutils希望它们可以解决这个问题,但徒劳无功。我无法添加 Node.js 包,jsdom因为显然它无法在已部署的 Meteor 应用程序中工作。

知道如何实现我想要做的事情吗?

Mus*_*afa 2

您不能真正依赖客户端会发生的情况。即使 Ubuntu 和 Windows 也会因为不同的提示、抗锯齿而显示不同的字体,并且它们可能会影响显示的大小。

如果你修改你的span的css如下,当它的文本大于所需的空间时,无论如何,剩余的将显示为...

max-width: 10%;
border: 1px #000 solid; // JUST TO SEE the effect clearly
width: 10%;
overflow: hidden;
height: 20px;
text-overflow: ellipsis;
display: block;
white-space: nowrap;
Run Code Online (Sandbox Code Playgroud)

**请注意,您需要一个合适的高度值,否则文本将落到底部,而无法实现您想要的效果。

尝试http://jsfiddle.net/sG6H2/