Created
November 4, 2010 16:28
-
-
Save ternus/662737 to your computer and use it in GitHub Desktop.
Fits a string to a given pixel size
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 fitString(str, size, strclass) { | |
// Fits a string to a given pixel size | |
// Based on a solution from stackoverflow.com | |
var nstr = str; | |
var tmp = document.createElement("span"); | |
tmp.className = strclass; | |
tmp.style.visibility = "hidden"; | |
tmp.style.padding = "0px"; | |
document.body.appendChild(tmp); | |
tmp.innerHTML = nstr; | |
// we use a binary search to determine the appropriate size | |
if (tmp.offsetWidth > size) { | |
var minLength = 0; | |
var maxLength = str.length; | |
var curLength; | |
while(true){ | |
curLength = minLength + Math.floor((maxLength - minLength) / 2); | |
tmp.innerHTML = str.substring(0, curLength) + '…'; | |
console.debug("size:" + size + ", min: " + minLength + ", max: " + maxLength + ", cur: " + curLength + " width: " + tmp.offsetWidth); | |
if (curLength == maxLength || curLength == minLength) { | |
break; | |
} else if (tmp.offsetWidth > size) { | |
maxLength = curLength; | |
} else { | |
minLength = curLength; | |
} | |
}; | |
nstr = str.substring(0, curLength) + '…'; | |
} | |
document.body.removeChild(tmp); | |
return nstr; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment