Calculate text width with JavaScript

前端 未结 24 1619
陌清茗
陌清茗 2020-11-21 05:08

I\'d like to use JavaScript to calculate the width of a string. Is this possible without having to use a monospace typeface?

If it\'s not built-in, my only idea is t

24条回答
  •  不思量自难忘°
    2020-11-21 05:20

    Rewritten my answer from scratch (thanks for that minus). Now function accepts a text and css rules to be applied (and doesn't use jQuery anymore). So it will respect paddings too. Resulting values are being rounded (you can see Math.round there, remove if you want more that precise values)

    function getSpan(){
        const span = document.createElement('span')
        span.style.position = 'fixed';
        span.style.visibility = 'hidden';
        document.body.appendChild(span);
        return span;
    }
    
    function textWidth(str, css) {
        const span = getSpan();
        Object.assign(span.style, css || {});
        span.innerText = str;
        const w = Math.round(span.getBoundingClientRect().width);
        
        span.remove();
        
        return w;
    }
    
    
    const testStyles = [
      {fontSize: '10px'},
      {fontSize: '12px'},
      {fontSize: '60px'},
      {fontSize: '120px'},
      {fontSize: '120px', padding: '10px'},
      {fontSize: '120px', fontFamily: 'arial'},
      {fontSize: '120px', fontFamily: 'tahoma'},
      {fontSize: '120px', fontFamily: 'tahoma', padding: '5px'},
    ];
    
    const ul = document.getElementById('output');
    testStyles.forEach(style => {
      const li = document.createElement('li');
      li.innerText = `${JSON.stringify(style)} > ${textWidth('abc', style)}`;
      ul.appendChild(li);
    });

    提交回复
    热议问题