Get string length in pixels using JavaScript

This question already has an answer here:

  • Get string length in pixels with JavaScript 2 answers
  • Determine Pixel Length of String in Javascript/jQuery? 7 answers

  • Put your text in a <span> and use JavaScript to measure the width of your <span> .

    HTML:

    <span id="text">Dummy text</span>
    

    JavaScript:

    var textWidth = document.getElementById("text").clientWidth;
    

    jQuery:

    $('#text').width();
    

    You can create some inline element ( span , for example), set your string as element's content ( innerHTML ), insert it into document (append to some element) and get it's width ( clientWidth ).

    There is no other way to measure length of string in pixels because it depends on font style.


    由于字符串的像素长度将根据独立应用的CSS属性(如字体,重量和大小)而发生变化,因此我无法在JS中看到这种可能性。

    链接地址: http://www.djcxy.com/p/69318.html

    上一篇: 根据它们的含义来比较句子

    下一篇: 使用JavaScript获取字符串的像素长度