我需要在 CSS 中找到 HTML textarea 元素中字符的宽度
px
.
最好的解决方案是使用一个 JavaScript 函数,它接受一个字符并返回它的宽度,并且必须处理特殊字符,如控制字符(
\u0001
、\u0096
、\uFFFD
等)。如果它也给定文本区域中字符的索引,使用 Tabs。
我已经有一个函数可以做到这一点(链接在这里;我的项目是开源的,在 GitHub 上) 使用 HTML5 文本区域并在 Chromium 上工作,但它在 Firefox 中中断,特别是因为 Firefox 在文本区域中以不同方式呈现控制字符( “十六进制框”)到其他元素。
getCharacterWidth(char) {
// Force zero-width characters
if(new RegExp("\u00AD|\u02de|[\u0300-\u036F]|[\u0483-\u0489]|\u200b").test(char) ) { return 0 }
// Non-renderable ASCII characters should all be rendered at same size
if(char != "\u0096" && new RegExp("[\u{0000}-\u{001F}]|[\u{007F}-\u{009F}]", "g").test(char)) {
let fallbackWidth = this.getCharacterWidth("\u0096");
return fallbackWidth;
}
// Lazy-load - TODO: Get a cleaner way of doing this
if(char in this.cachedWidths) {
return this.cachedWidths[char];
}
// Try to get width
let width = this.canvasContext.measureText(char).width;
this.canvasContext.fillText(char, 100, 100);
if(width > 20) {
width /= 2; // Fix double-width-in-canvas Firefox bug
} else if(width == 0 && char != "\u0096") {
let fallbackWidth = this.getCharacterWidth("\u0096");
return fallbackWidth; // In Firefox some control chars don't render, but all control chars are the same width
}
this.cachedWidths[char] = width;
return width;
}
我非常感谢这里的建议,或者在 GitHub 上从 display-special-chars
分支分叉的项目中的 PR。谢谢你的帮助。
看看这段代码。
// create a new canvas element
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
// set the font size and type
ctx.font = '16px Arial';
// get the width of the character 'A'
const charWidth = ctx.measureText('A').width;
console.log(`The width of the character 'A' is ${charWidth}px`);
我想这对你有帮助。