Calculate text width with JavaScript

前端 未结 24 1627
陌清茗
陌清茗 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:19

    Without jQuery:

    String.prototype.width = function (fontSize) {
        var el,
            f = fontSize + " px arial" || '12px arial';
        el = document.createElement('div');
        el.style.position = 'absolute';
        el.style.float = "left";
        el.style.whiteSpace = 'nowrap';
        el.style.visibility = 'hidden';
        el.style.font = f;
        el.innerHTML = this;
        el = document.body.appendChild(el);
        w = el.offsetWidth;
        el.parentNode.removeChild(el);
        return w;
    }
    
    // Usage
    "MyString".width(12);
    

提交回复
热议问题