Javascript:计算div中的可见字符 [英] Javascript: Count visible characters in div
问题描述
我有一个 div
,它包含任意长度的文本(长度 S
的字符串)固定尺寸。超过一定长度(让我们称为 L
),文本被截断,文本的其余部分不再可见。 (技术上来说,范围 [0,L)
是可见的,范围 [L,S)
。
I have a div
which contains text (a string of length S
) of an arbitrary length, but a fixed size. Beyond a certain length (let's call it L
), the text is truncated and the remainder of the text is no longer visible. (Technically speaking, the range [0,L)
is visible, the range [L,S)
is not).
我想要做的是通过仅计数 visible可以查找文本的长度 L
div
中的字符数。任何超出截止点的字符都应忽略。
What I want to do is find the length L
for the text by counting only the visible number of characters in the div
. Any characters beyond the cut-off point should be disregarded.
我很高兴使用第三方库,如jQuery等,如果这将完成工作!
I'm happy to use 3rd party libraries like jQuery etc if that will get the job done!
推荐答案
这是我修剪文本的一个函数:
Here is a function I made for trimming text:
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;
}
我使用二进制搜索找到适合特定宽度的文本。
为了使用函数,你必须这样调用:
I'm using binary search for finding the text that fits into a specific width. In order to use the function, you must call it like this:
getTextThatFits(yourText, divWidth, fontSize, fontName, fontWeight=optional)
这篇关于Javascript:计算div中的可见字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!