JavaScript 计算文本的宽度
通过使用DOM元素或使用measureText()方法来计算文本区域的宽度在JavaScript中是非常简单的。下面将使用示例来解释这两种方法。
方法1:创建一个新的DOM元素并测量其宽度
使用createElement()方法创建一个新的“span”元素,然后使用appendChild()方法将其添加到元素的body中。 使用该元素的style属性设置属性,如字体、字体大小、高度、宽度、whiteSpace和位置。将字体设置为所需的字符串。将字体大小设置为以像素为单位的字符串。将高度和宽度属性设置为“auto”。将位置属性设置为“absolute”,将whiteSpace属性设置为“no-wrap”。使用innerHTML属性指定要测量的文本。使用clientWidth属性获取其元素的宽度。此值将表示文本的宽度(以像素为单位)。然后使用removeChild()方法来移除该元素。
示例:
<h1 style="color: green">
GeeksforGeeks
</h1>
<b>
Calculate text width
with JavaScript
</b>
<p>
Text to calculate width is
"Hello World"
</p>
<p>Font size of the text is 16px</p>
<p>
Width of the text is:
<span class="output"></span>
</p>
<button onclick="getTextWidth()">
Calculate text width
</button>
<script type="text/javascript">
function getTextWidth() {
text = document.createElement("span");
document.body.appendChild(text);
text.style.font = "times new roman";
text.style.fontSize = 16 + "px";
text.style.height = 'auto';
text.style.width = 'auto';
text.style.position = 'absolute';
text.style.whiteSpace = 'no-wrap';
text.innerHTML = 'Hello World';
width = Math.ceil(text.clientWidth);
formattedWidth = width + "px";
document.querySelector('.output').textContent
= formattedWidth;
document.body.removeChild(text);
}
</script>
输出:
方法2:使用 的measureText()方法
通过使用createElement()方法创建一个新的”canvas”元素。使用getContext()方法并将值”2d”作为参数来访问绘制图形所需的2D上下文。这个上下文将用于操作画布中的文本。使用font属性来指定字体。字体字符串使用与CSS字体规范相同的语法。使用measureText()方法计算文本的尺寸。将要测量的文本传递给这个方法。它返回一个包含关于测量文本的信息的TextMetrics对象。该TextMetrics对象的width属性用于获取文本的宽度。宽度可以是浮点数值,因此使用Math.ceil()函数找到浮点数的最小整数并返回一个整数。这个值是测量文本的宽度(以像素为单位)。
示例:
<h1 style="color: green">
GeeksforGeeks
</h1>
<b>Calculate text width with JavaScript</b>
<p>
Text to calculate width is
"Geeks For Geeks"
</p>
<p>Font size of the text is 16px</p>
<p>
Width of the text is:
<span class="output"></span>
</p>
<button onclick="getTextWidth()">
Calculate text width
</button>
<script type="text/javascript">
function getTextWidth() {
inputText = "Geeks For Geeks";
font = "16px times new roman";
canvas = document.createElement("canvas");
context = canvas.getContext("2d");
context.font = font;
width = context.measureText(inputText).width;
formattedWidth = Math.ceil(width) + "px";
document.querySelector('.output').textContent
= formattedWidth;
}
</script>
输出: