Fit text perfectly inside a div (height and width) without affecting the size of the div

前端 未结 9 1846
盖世英雄少女心
盖世英雄少女心 2020-12-02 17:07

I apologise in advance as I know this question has come up many times before but I just can\'t seem to find the right solution (and believe me I\'ve tried a few!)

Ba

9条回答
  •  生来不讨喜
    2020-12-02 18:04

    Here's my version. This is build with ES6 on a React project.

    export function autoSizeText(container, attempts=30) {
      let setChildrenToInheritFontSize = ( el ) => {
        el.style.fontSize = 'inherit';
        _.each( el.children, (child) => {
          setChildrenToInheritFontSize( child );
        });
      };
    
    
      let resizeText = (el) => {
        attempts--;
        let elNewFontSize;
        if( el.style.fontSize === "" ||  el.style.fontSize === "inherit" ||  el.style.fontSize === "NaN" ){
          elNewFontSize = '32px'; // largest font to start with
        } else {
          elNewFontSize = (parseInt(el.style.fontSize.slice(0, -2)) - 1) + 'px';
        }
        el.style.fontSize = elNewFontSize;
    
        // this function can crash the app, so we need to limit it
        if( attempts <= 0 ) {
          return;
        }
    
        if ( (el.scrollWidth > el.offsetWidth) || (el.scrollHeight > el.offsetHeight)) {
          resizeText(el);
        }
      };
      setChildrenToInheritFontSize( container );
      resizeText(container);
    }
    

提交回复
热议问题