zoukankan      html  css  js  c++  java
  • js 计算文字宽度

    方式1 利用canvas处理

    /*
    计算文字宽度
    text 需要计算宽度的文字 包括空格
    font 字体属性  比如  `12px sans-serif`
    */
    function getTextWidth(text, font) {
        // getTextWidth.canvas 这里主要为了复用一个canvas   getTextWidth.canvas就是一个全局变量
        // getTextWidth.任意变量 首次定义只能在getTextWidth函数内定义
        // 然后在其他函数内就可以定义 getTextWidth.其他变量  但是不建议这么使用 
        var canvas = getTextWidth.canvas || (getTextWidth.canvas = document.createElement("canvas"));
        var context = canvas.getContext("2d");
        context.font = font;
        // 不需要在画布上输出就可以计算文字的宽度
        var metrics = context.measureText(text);
        return metrics.width;
    }

    方式2 利用页面控件处理

    <html>
    <head>
    <style type="text/css">
    #ruler {
        position:absolute;
        visibility: hidden;
        white-space: nowrap;
        z-index: -900;
        /* white-space: pre 为了处理多空格计算宽度小的问题 */
        white-space: pre;
    }
    </style>
    </head>
    <body>
      <span id="ruler"></span>
    <script type="text/javascript">
    function(text, size, family) {
       var ruler = document.getElementById("ruler");
       ruler.style.fontSize = size;
       ruler.style.fontFamily = family;
      ruler.textContent = text;
     return ruler.clientWidth;
    }
    </script>
    </body>
    </html>

      

  • 相关阅读:
    CF763C Timofey and Remoduling
    CF762E Radio Stations
    CF762D Maximum Path
    CF763B Timofey and Rectangles
    URAL1696 Salary for Robots
    uva10884 Persephone
    LA4273 Post Offices
    SCU3037 Painting the Balls
    poj3375 Network Connection
    Golang zip压缩文件读写操作
  • 原文地址:https://www.cnblogs.com/rchao/p/15009768.html
Copyright © 2011-2022 走看看