有時候,您必須將字符串放在某個像素寬度內。該功能試圖有效地這樣做。請發表您的建議或重構低於:)很好地截斷一個字符串以適合給定的像素寬度
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