Calculate text width with JavaScript

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

    The width and heigth of a text can be obtained with clientWidth and clientHeight

    var element = document.getElementById ("mytext");
    
    var width = element.clientWidth;
    var height = element.clientHeight;
    

    make sure that style position property is set to absolute

    element.style.position = "absolute";
    

    not required to be inside a div, can be inside a p or a span

提交回复
热议问题