html - 文本受它们占用的空间量限制

标签 html css angular material-design

有没有办法根据输入框占用的大小来限制可以放入输入框的字母数量?

例如,W 和 M 占用的空间足以放置其中的 34 个。

enter image description here

但如果我使用普通句子,与 W 和 M 相比,相同数量的字母只占一半的大小。

enter image description here

我想要的是只要输入字段的大小足够大,我基本上可以写任何东西。 这可能吗?

最佳答案

首先,您可以使用如下方式访问输入的大小:

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/

相关文章:

jquery - 使用第 n 个 child

javascript - 检查数组中的项目,是否有打印 JS/HTML 中的特定文本

css - Bootstrap 站点结构 - 重新定位/流动导航

javascript - 单击单元格时选择单选按钮

javascript - 仅当设置新帧时才将动画绘制到 Canvas 上?

css - 文本显示在 span 后面

html - 与表格单元格垂直对齐不起作用

angular - 具有 Ionic 3 延迟加载的 native 存储模块

Angular 4,<md-checkbox> 没有双向绑定(bind)

angularjs - Angular 2.0 是否有类似于 Angular 1 中的 `$setPristine` 函数的东西?