Advertisement
Guest User

Untitled

a guest
Jul 21st, 2017
42
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.52 KB | None | 0 0
  1. function maximizeFontSize(elem, maxWidth, maxHeight, opt_dontChangeFontSize) {
  2. var canBeBigger,
  3. display = elem.style.display,
  4. fontSize = elem.style.fontSize,
  5. font = elem.style.font,
  6. computedFont = window.getComputedStyle(elem, null).getPropertyValue('font'),
  7. doc = elem.ownerDocument,
  8. parentNode = elem.parentNode,
  9. tempParent = doc.createElement('div'),
  10. nextSibling = elem.nextSibling,
  11. newFontSize = 0.5,
  12. diff = 0.5;
  13.  
  14. elem.style.display = 'inline-block';
  15. elem.style.font = computedFont;
  16.  
  17. tempParent.style.display = 'block';
  18. tempParent.style.width = maxWidth;
  19. tempParent.style.height = maxHeight;
  20. tempParent.style.overflow = 'hidden';
  21.  
  22. doc.body.appendChild(tempParent);
  23. tempParent.appendChild(elem);
  24.  
  25. do {
  26. newFontSize += diff;
  27. elem.style.fontSize = newFontSize + 'px';
  28. if (canBeBigger = (elem.clientWidth <= maxWidth && elem.clientHeight <= maxHeight)) {
  29. diff *= 2;
  30. }
  31. else {
  32. newFontSize -= diff;
  33. diff /= 2;
  34. }
  35. } while((!canBeBigger && newFontSize > 0.5) || diff >= 1);
  36.  
  37. if (opt_dontChangeFontSize || !canBeBigger) {
  38. elem.style.fontSize = fontSize;
  39. }
  40.  
  41. doc.body.removeChild(tempParent);
  42. parentNode.insertBefore(elem, nextSibling);
  43. elem.style.display = display;
  44.  
  45. if (font) {
  46. elem.style.font = (opt_dontChangeFontSize || !canBeBigger) ? font : font.replace(/\b(\d+(\.\d+)?|\.\d+)[A-Za-z]+\b/, newFontSize + 'px');
  47. }
  48. else {
  49. delete elem.style.font;
  50. }
  51.  
  52. return canBeBigger ? newFontSize : undefined;
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement