当前位置: 代码迷 >> 综合 >> JS测量文字的宽度px和高度px
  详细解决方案

JS测量文字的宽度px和高度px

热度:11   发布时间:2023-09-27 01:53:25.0

如果单纯测量文字宽度px,比较常用的方法是使用canvas的context.measureText:

function measureUseCanvas(fontSize, fontFamily, text) {var canvas = document.createElement("canvas");var context = canvas.getContext("2d");context.font = fontSize + " " + fontFamily;var result = context.measureText(text);return result.width
}

由于canvas只能测量宽度,若同时需要获得文字高度的px,则需要使用其他方法:

function measureText(fontSize, fontFamily, text) {var span = document.createElement("span");var result = {width: 0,height: 0};span.style.visibility = "hidden";span.style.fontSize = fontSize;//文字大小span.style.fontFamily = fontFamily;//字体span.style.display = "inline-block";document.body.appendChild(span);if (typeof span.textContent != "undefined") {span.textContent = text;} else {span.innerText = text;}//使用window.getComputedStyle方法获取result.width = parseFloat(window.getComputedStyle(span).width) - span.offsetWidth;result.height = parseFloat(window.getComputedStyle(span).height) - span.offsetHeight;return result;
}

  相关解决方案