Created
November 12, 2008 20:40
-
-
Save Aeon/24261 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function fitStringToSize(str,len) { | |
var result = str; | |
var span = document.createElement("span"); | |
span.style.visibility = 'hidden'; | |
span.style.padding = '0px'; | |
document.body.appendChild(span); | |
// on first run, check if string fits into the length already. | |
span.innerHTML = result; | |
if(span.offsetWidth > len) { | |
var posStart = 0, posMid, posEnd = str.length; | |
while (true) { | |
// Calculate the middle position | |
posMid = posStart + Math.ceil((posEnd - posStart) / 2); | |
// Break the loop if this is the last round | |
if (posMid==posEnd || posMid==posStart) break; | |
span.innerHTML = str.substring(0,posMid) + '…'; | |
// Test if the width at the middle position is | |
// too wide (set new end) or too narrow (set new start). | |
if ( span.offsetWidth > len ) posEnd = posMid; else posStart=posMid; | |
} | |
//Escape < and >, eliminate trailing space and a widow character if one is present. | |
result = str.substring(0,posStart).replace("<","<").replace(">",">").replace(/(\s.)?\s*$/,'') + '…'; | |
} | |
document.body.removeChild(span); | |
return result; | |
} | |
function getShortLink(str,len,url) | |
{ | |
return '<a title="' + str.replace("\"",""") + '" href="'+ url +'">' + fitStringToSize(str,len) + '<\/a>'; | |
} | |
function getShortAbbr(str,len) | |
{ | |
return '<abbr title="' + str.replace("\"",""") + '">' + fitStringToSize(str,len) + '<\/abbr>'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment