前言:由于像素和字体大小,字节(特别是 UTF-8)等限制因素,所以我们不能直接知道一个字符串所占的实际宽度。
这里提供几种比较测量方法:
1、通过Canvas测
const getTextWidth = (text:string, font:string = "normal 12pt arial"): number => {
if (!text) return 12;
const canvas = getTextWidth.canvas || (getTextWidth.canvas = document.createElement("canvas"));
const context = canvas.getContext("2d");
context.font = font;
const metrics = context.measureText(text);
return metrics.width;
}
或者
let tCanvas = null;
const getTextWidth = (text:string, font:string = "normal 12pt sans-serif"): number => {
if (!text) return 12;
let canvas = tCanvas || (tCanvas = document.createElement("canvas"));
const context = canvas.getContext("2d");
context.font = font;
const metrics = context.measureText(text);
return metrics.width;
}
使用:
const width = getTextWidth("hello there!", "bold 12pt arial")
console.log('width:', width)
2、通过 DOM 测量,这种方法在字符串中含有多个空格时,测出来的宽度会一样
// 计算单行文本宽度
const getTextWidth = (text: string = "", font: string = "12px"): number => {
if (!text) return 12;
const dom = document.createElement("span") as HTMLElement;
dom.style.display = "inline-block";
dom.style.fontSize = font;
dom.style.whiteSpace = "nowrap";
dom.textContent = text;
document.body.appendChild(dom);
const width = dom.clientWidth;
document.body.removeChild(dom);
return width;
};
3、用个 visibility: hidden 的浮动的层来计算字符串宽度。
在添加的 div 容器里把样式设置为和你实际的 div 一样。
<!DOCTYPE html>
<html>
<head>
<script src='jquery.min.js'></script>
</head>
<body>
<div
id='labelText'
style='color:black; line-height:1.2; white-space: nowrap; position:fixed;
top:0px; left:0px; display:block; visibility:visible;'
></div>
<script>
var str = 'Live like you were dying, Love because you do.';
str = str.substring(0, str.length);
$('#labelText').css({
'font-size': '12px',
'font-family': 'Microsoft YaHei'
}).html(str);
var width = $('#labelText').width();
console.log(width);
</script>
</body>
</html>
计算高度也一样。
注意:最后别忘了移除额外添加的 div!
点赞加关注,永远不迷路
网友评论