Calculate text width with JavaScript

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

    Create a DIV styled with the following styles. In your JavaScript, set the font size and attributes that you are trying to measure, put your string in the DIV, then read the current width and height of the DIV. It will stretch to fit the contents and the size will be within a few pixels of the string rendered size.

    var fontSize = 12;
    var test = document.getElementById("Test");
    test.style.fontSize = fontSize;
    var height = (test.clientHeight + 1) + "px";
    var width = (test.clientWidth + 1) + "px"
    
    console.log(height, width);
    #Test
    {
        position: absolute;
        visibility: hidden;
        height: auto;
        width: auto;
        white-space: nowrap; /* Thanks to Herb Caudill comment */
    }
    abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ

提交回复
热议问题