Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function maximizeFontSize(elem, maxWidth, maxHeight, opt_dontChangeFontSize) {
- var canBeBigger,
- display = elem.style.display,
- fontSize = elem.style.fontSize,
- font = elem.style.font,
- computedFont = window.getComputedStyle(elem, null).getPropertyValue('font'),
- doc = elem.ownerDocument,
- parentNode = elem.parentNode,
- tempParent = doc.createElement('div'),
- nextSibling = elem.nextSibling,
- newFontSize = 0.5,
- diff = 0.5;
- elem.style.display = 'inline-block';
- elem.style.font = computedFont;
- tempParent.style.display = 'block';
- tempParent.style.width = maxWidth;
- tempParent.style.height = maxHeight;
- tempParent.style.overflow = 'hidden';
- doc.body.appendChild(tempParent);
- tempParent.appendChild(elem);
- do {
- newFontSize += diff;
- elem.style.fontSize = newFontSize + 'px';
- if (canBeBigger = (elem.clientWidth <= maxWidth && elem.clientHeight <= maxHeight)) {
- diff *= 2;
- }
- else {
- newFontSize -= diff;
- diff /= 2;
- }
- } while((!canBeBigger && newFontSize > 0.5) || diff >= 1);
- if (opt_dontChangeFontSize || !canBeBigger) {
- elem.style.fontSize = fontSize;
- }
- doc.body.removeChild(tempParent);
- parentNode.insertBefore(elem, nextSibling);
- elem.style.display = display;
- if (font) {
- elem.style.font = (opt_dontChangeFontSize || !canBeBigger) ? font : font.replace(/\b(\d+(\.\d+)?|\.\d+)[A-Za-z]+\b/, newFontSize + 'px');
- }
- else {
- delete elem.style.font;
- }
- return canBeBigger ? newFontSize : undefined;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement