JS计算⽂本字符串字节长度和像素长度的⽅法来源:
<!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 >qwe</span>
</body>
js验证字符串长度<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 = ateElement("canvas")),
context = Context("2d");
font && (context.font = font);
var metrics = asureText(this);
return metrics.width;
}
</script>
</html>

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。