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