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

时间:2018-10-19 08:24:42

标签: javascript html angular

具有这种情况:

Sample out put

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

html代码就是这样:

<textarea style="width:450px;"></textarea>

是否可以使用Angular4 +或Javascript实现此目的?

1 个答案:

答案 0 :(得分:6)

编辑:

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

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);
#widthTest
{
    position: absolute;
    visibility: hidden;
    height: auto;
    width: auto;
    white-space: nowrap; 
}
<div id="widthTest">
    FooBarEatsBarFoodBareFootWithBarFoo
</div>

如果您想要某个元素的宽度,可以使用 javascript 将文本放置在其中,您可以按照以下步骤操作:

document.getElementById("myTextArea").offsetWidth

document.getElementById("myTextArea").clientWidth

信息:

  

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

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

 <textarea id="myTextArea" style="width:450px;"></textarea>

如果要在角度组件代码中获取宽度:

someComponent.html:

 <textarea #myTextAreaRef style="width:450px;"></textarea>

someComponent.ts:

export class SystemComponent implements OnInit {

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

   someFunction() {
      console.log(this.myTextAreaRef.nativeElement.someAttribute)
   }