有没有办法根据输入框占用的大小来限制可以放入输入框的字母数量?
例如,W 和 M 占用的空间足以放置其中的 34 个。
但如果我使用普通句子,与 W 和 M 相比,相同数量的字母只占一半的大小。
我想要的是只要输入字段的大小足够大,我基本上可以写任何东西。 这可能吗?
最佳答案
首先,您可以使用如下方式访问输入的大小:
const ele = document.getElementById('yourInputId');
const eleStyle = window.getComputedStyle(ele);
const inputSize = {width: eleStyle.width, height: eleStyle.heigth};
然后,在另一种方法中,假设您知道文本的字体和字体大小(如果不知道,请查看 Angular 文档),您可以设置这样的方法:
pixelLength(txt: string, font: number) {
const canva = document.createElement('CANVAS');
const attr = document.createAttribute('id');
attr.value = 'myId';
canva.setAttributeNode(attr);
document.body.appendChild(canva);
const c: any = document.getElementById('myId');
const ctx = c.getContext('2d');
ctx.font = font.toString() + 'px Helvetica';
const result = ctx.measureText(txt).width;
document.body.removeChild(canva);
return result;
}
您可能想在自定义表单控件中调用此方法,以检查它是否会比 inputSize.width
长。
如果有什么不清楚的地方请告诉我;)
快乐的编码。
关于html - 文本受它们占用的空间量限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59410841/