如何使用JavaScript在HTML的TextArea中获取文本的宽度和高度?

Jac*_*mpi 4 html javascript angular

有这种情况:

样品放

需要获取red box文本区域内部的大小。基本上是文本的尺寸,而不是文本区域的尺寸。

html代码就是这样:

<textarea style="width:450px;"></textarea>
Run Code Online (Sandbox Code Playgroud)

有没有办法使用Angular4 +或Javascript实现这一目标?

iLu*_*gix 7

编辑:

要计算任意字符串的宽度,可以使用以下方法:

var fontSize = 12;
var widthTest = document.getElementById("widthTest");
widthTest.style.fontSize = fontSize;
var height = (widthTest.clientHeight + 1) + "px";
var width = (widthTest.clientWidth + 1) + "px"

console.log(height, width);
Run Code Online (Sandbox Code Playgroud)
#widthTest
{
    position: absolute;
    visibility: hidden;
    height: auto;
    width: auto;
    white-space: nowrap; 
}
Run Code Online (Sandbox Code Playgroud)
<div id="widthTest">
    FooBarEatsBarFoodBareFootWithBarFoo
</div>
Run Code Online (Sandbox Code Playgroud)

如果您想要某个元素的宽度,则可以使用javascript放置文本,您可以像这样:

document.getElementById("myTextArea").offsetWidth
Run Code Online (Sandbox Code Playgroud)

要么

document.getElementById("myTextArea").clientWidth
Run Code Online (Sandbox Code Playgroud)

信息:

offsetWidth包括边框宽度,clientWidth不包括

在您的情况下,您需要将id应用于文本区域,例如:

 <textarea id="myTextArea" style="width:450px;"></textarea>
Run Code Online (Sandbox Code Playgroud)

如果要在角度分量代码中获取宽度:

someComponent.html:

 <textarea #myTextAreaRef style="width:450px;"></textarea>
Run Code Online (Sandbox Code Playgroud)

someComponent.ts:

export class SystemComponent implements OnInit {

   @ViewChild('myTextAreaRef') public myTextAreaRef;
   ...
   ..

   someFunction() {
      console.log(this.myTextAreaRef.nativeElement.someAttribute)
   }
Run Code Online (Sandbox Code Playgroud)