來源:js獲取字符長度並計算px寬度 - 【雲】風過無痕 - 博客園 (cnblogs.com)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>JS計算文本字符串長度的兩種方法</title> </head> <body> <span style="font:normal 36px Robot;">qwe</span> </body> <script> // 字節長度 String.prototype.byteLength = function () { var length = 0; Array.from(this).map(function (char) { // 字符編碼大於255,說明是雙字節字符 if (char.charCodeAt(0) > 255) { length += 2; } else { length++; } }); return length; } // 獲取文本px寬度* @param font{String}: 字體樣式 eg: normal 36px Robot String.prototype.pxWidth = function (font) { 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; } </script> </html>