Calculate text width with JavaScript

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

    You can use the canvas so you don't have to deal so much with css properties:

    var canvas = document.createElement("canvas");
    var ctx = canvas.getContext("2d");
    ctx.font = "20pt Arial";  // This can be set programmaticly from the element's font-style if desired
    var textWidth = ctx.measureText($("#myElement").text()).width;
    

提交回复
热议问题