这是我为修剪文本而制作的函数:
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;
}
我使用二分搜索来查找适合特定宽度的文本。
为了使用该函数,您必须像这样调用它:
getTextThatFits(yourText, divWidth, fontSize, fontName, fontWeight=optional)