Javascript:计算div中的可见字符

Jon*_*lis 5 html javascript jquery count

我有一个div包含S任意长度的文本(长度的字符串),但是固定的大小.超过一定长度(让我们称之为L),文本被截断,文本的其余部分不再可见.(从技术上讲,范围[0,L)是可见的,范围[L,S)不是).

我想要做的是L通过仅计算文本中可见的字符数来找到文本的长度div.超出截止点的任何字符都应该被忽略.

我很高兴使用jQuery等第三方库,如果能完成工作的话!

gab*_*ish 2

这是我为修剪文本而制作的函数:

function getTextThatFits(txt, w, fSize, fName, fWeight) {
    if (fWeight === undefined)
        fWeight = "normal";

    var auxDiv = $("<div>").addClass("auxdiv").css ({
        fontFamily : fName,
        fontSize : parseInt(fSize) + "px",
        position: "absolute",
        height: "auto",
        marginLeft : "-1000px",
        marginTop : "-1000px",
        fontWeight: fWeight,
        width: "auto"
    })
    .appendTo($("body"))
    .html(txt);

    var ww = (auxDiv.width() + 1);
    var str = txt;

    if (ww > w)
    {
        var i = 1, p = 1, u = txt.length, sol = 0;

        while (p <= u)
        {
            i = (p + u) >> 1;
            str = txt.slice(0, i);
            auxDiv.html(str);
            ww = (auxDiv.width() + 1);
            if (ww <= w) {
                sol = i;
                p = i + 1;
            }
            else u = i - 1;
        }

        str = txt.slice(0, sol);
    }
    $(".auxdiv").remove();
    auxDiv.remove();
    return str.length;
}
Run Code Online (Sandbox Code Playgroud)

我使用二分搜索来查找适合特定宽度的文本。为了使用该函数,您必须像这样调用它:

getTextThatFits(yourText, divWidth, fontSize, fontName, fontWeight=optional)
Run Code Online (Sandbox Code Playgroud)