有时候,您必须将字符串放在某个像素宽度内。该功能试图有效地这样做。请发表您的建议或重构低于:)很好地截断一个字符串以适合给定的像素宽度
function fitStringToSize(str,len) {
var shortStr = str;
var f = document.createElement("span");
f.style.display = 'hidden';
f.style.padding = '0px';
document.body.appendChild(f);
// on first run, check if string fits into the length already.
f.innerHTML = str;
diff = f.offsetWidth - len;
// if string is too long, shorten it by the approximate
// difference in characters (to make for fewer iterations).
while(diff > 0)
{
shortStr = substring(str,0,(str.length - Math.ceil(diff/5))) + '…';
f.innerHTML = shortStr;
diff = f.offsetWidth - len;
}
while(f.lastChild) {
f.removeChild(f.lastChild);
}
document.body.removeChild(f);
// if the string was too long, put the original string
// in the title element of the abbr, and append an ellipsis
if(shortStr.length < str.length)
{
return '<abbr title="' + str + '">' + shortStr + '</abbr>';
}
// if the string was short enough in the first place, just return it.
else
{
return str;
}
}
UPDATE: @下面一些的解决方案要好得多;请使用它。
更新2: 现在的代码发布为gist;随时分叉和提交补丁:)
非常好,谢谢。/5是基于在我的应用程序中使用眼球来选择的(m是10px,f是3px)。这实际上是一种垃圾,因为字体大小会根据字符串将放置的div的样式而变化,所以理想情况下我们不会追加到body,而是添加到div。 – Aeon 2008-11-12 18:59:06