js获取字符长度并计算px宽度


1、为 String 扩展原型方法 byteLength(),该方法将根据每个字符编码,判断当前字符是单字节还是双字节,然后统计字符串的字节长度。

String.prototype.byteLength = function() {
    var length = 0;
    Array.from(this).map(function(char){
        if(char.charCodeAt(0)>255) {//字符编码大于255,说明是双字节字符
            length += 2;
        }else {
            length++;
        }
    });
    
    return length;
}

 

测试:

 

2、计算文本在页面所占px宽度 -- 扩展String原型方法pxWidth

/**
* 获取文本px宽度
* @param font{String}: 字体样式
**/
String.prototype.pxWidth = function(font) { // re-use canvas object for better performance var canvas = String.prototype.pxWidth.canvas || (String.prototype.pxWidth.canvas = document.createElement("canvas")), context = canvas.getContext("2d"); font && (context.font = font); var metrics = context.measureText(this); return metrics.width; }

 测试:

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM