JS 计算任意字符串宽度
PS: 是宽度不是长度!
由于像素和字体大小,字节(特别是 UTF-8)等限制因素,所以我们不能直接知道一个字符串所占的实际宽度。
这里提供几种比较测量方法:
1、通过Canvas测
/**
* Uses canvas.measureText to compute and return the width of the given text of given font in pixels.
* @param {String} text The text to be rendered.
* @param {String} font The css font descriptor that text is to be rendered with (e.g. "bold 14px verdana").
* @see https://stackoverflow.com/questions/118241/calculate-text-width-with-javascript/21015393#21015393
function getTextWidth(text, font) {
// re-use canvas object for better performance
var canvas = getTextWidth.canvas || (getTextWidth.canvas = document.createElement("canvas"));
var context = canvas.getContext("2d");
context.font = font;
var metrics = context.measureText(text);
return metrics.width;
console.log(getTextWidth("hello there!", "bold 12pt arial")); // close to 86
2、通过 DOM 测量,这种方法在字符串中含有多个空格时,测出来的宽度会一样,
例如: ''天猫旗舰店 49.67%(tmall)'' 和 ''天猫旗舰店 49.67%(tmall)'' 测出来的宽度都为 165(此值可能会有差异)
function getTextWidth(str = '') {
const dom = document.createElement('span');
dom.style.display = 'inline-block';
dom.textContent = '天猫旗舰店 49.67%(tmall)';
document.body.appendChild(dom);
const width = dom.clientWidth;
console.log(dom.clientWidth);
document.body.removeChild(dom);
return width;
}
3、用个 visibility: hidden 的浮动的层来计算字符串宽度。
在添加的 div 容器里把样式设置为和你实际的 div 一样。
<!DOCTYPE html>
<script src='jquery.min.js'></script>
</head>
id='labelText'
style='color:black; line-height:1.2; white-space: nowrap; position:fixed;
top:0px; left:0px; display:block; visibility:visible;'
<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!
Code:
let tCanvas = null;
getTextWidth(text, font = 'normal 12px sans-serif') {
// re-use canvas object for better performance
const canvas = tCanvas || (tCanvas = document.createElement('canvas'));
const context = canvas.getContext('2d');
context.font = font;
return context.measureText(text).width;
addStrWidthViaBlank(str, width) {
// 这个函数只适用于'xxx xx'形式的字符串(即原串就含有空格)
if (width <= 0 || (this.getTextWidth(str) >= width)) {
return str;
let tStr = str;
let tWidth = 0;
while (tWidth < width) {
tStr = tStr.replace(/(.*) /, '$1 ');