Created
September 3, 2011 01:12
-
-
Save miceno/1190342 to your computer and use it in GitHub Desktop.
Ellipsis mediante JavaScript
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
var ellipsisId= 'ellipsis_test_element'; | |
var ellipsisElement= null; | |
function insertEllipsisElement(){ | |
if( !ellipsisElement){ | |
ellipsisElement= document.createElement( 'div'); | |
ellipsisElement.id= ellipsisId; | |
document.body.appendChild( ellipsisElement); | |
} | |
} | |
function substring( text, i, f){ | |
return text.substr( i, f); | |
} | |
this.autoEllipseText=function(element, text, width) | |
{ | |
insertEllipsisElement(); | |
var inSpan= document.createElement( 'span'); | |
inSpan.id= "ellipsisSpan"; | |
inSpan.className= element.className; | |
inSpan.style.whiteSpace="nowrap"; | |
inSpan.style.visibility="hidden"; | |
var returnText= text; | |
ellipsisElement.appendChild( inSpan); | |
inSpan.innerHTML = text; | |
if(inSpan.offsetWidth > width) | |
{ | |
var i = 0; | |
inSpan.innerHTML = ''; | |
returnText= binarySearch( inSpan, text, width); | |
// returnText= bruteForceSearch( inSpan, text, width); | |
} | |
ellipsisElement.removeChild( inSpan); | |
return returnText; | |
} | |
function bruteForceSearch( inSpan, text, width){ | |
// Version of the algorithm with brute force search | |
var i= 0; | |
while( inSpan.offsetWidth < (width) && i < text.length) | |
{ | |
i++; | |
inSpan.innerHTML = text.substr(0,i) + '…'; | |
} | |
return text.substr( 0, i-1) + '&hellip'; | |
} | |
function binarySearch( inSpan, text, width){ | |
var left= 0; | |
var right= text.length; | |
var c= right; | |
// Version of the algorithm with binary search | |
while ((c = Math.floor((right + left) / 2)) > left) { | |
inSpan.innerHTML = text.substr(0, c) + '…'; | |
if ( inSpan.offsetWidth > width) right = c; | |
else left = c; | |
} | |
return text.substr( 0, c) + '&hellip'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment