Created
August 4, 2011 14:15
-
-
Save rbarazi/1125245 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 getHeight(elementStyle) { | |
return parseInt(elementStyle.height) + parseInt(elementStyle["margin-top"]) + parseInt(elementStyle["margin-bottom"]); | |
} | |
function trimText(element, elementHeight, maxHeight) { | |
var tmpText = element.innerHTML; | |
var words = tmpText.split(" "); | |
var min = 0; | |
var max = words.length; | |
var mid = Math.ceil((max + min) / 2); | |
do { | |
mid = Math.ceil((max + min) / 2); | |
element.innerHTML = words.slice(0, mid).join(" "); | |
elementHeight = getHeight(window.getComputedStyle(element)); | |
if (elementHeight > maxHeight) { | |
max = mid; | |
} else { | |
min = mid - 1; | |
} | |
} while((mid - min) > 1 || (max - mid) > 1) | |
if (elementHeight > maxHeight) { | |
element.innerHTML = ""; | |
elementHeight = getHeight(window.getComputedStyle(element)); | |
} | |
return elementHeight; | |
} | |
function trimArticles(articlesSelector) { | |
var articles = document.querySelectorAll(articlesSelector); | |
var article; | |
for (var i = 0; i< articles.length; i++) { | |
article = articles[i]; | |
var articleStyle = window.getComputedStyle(article); | |
var maxHeight = parseInt(articleStyle.height) - parseInt(articleStyle["padding-top"]) - parseInt(articleStyle["padding-bottom"]); | |
var element, elementStyle, elementHeight; | |
for (var j = 0; j < article.children.length; j++) { | |
element = article.children[j]; | |
elementStyle = window.getComputedStyle(element); | |
if (elementStyle["float"] != "none") { | |
continue; | |
} | |
elementHeight = getHeight(elementStyle); | |
if (maxHeight > 0) { | |
if (elementHeight > maxHeight) { | |
elementHeight = trimText(element, elementHeight, maxHeight); | |
} | |
} else { | |
element.innerHTML = ""; | |
elementHeight = getHeight(window.getComputedStyle(element)); | |
} | |
maxHeight = maxHeight - elementHeight; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment