繁体   English   中英

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

[英]How to get text width and height inside a TextArea in HTML using JavaScript?

有这种情况:

样品输出

需要获得textarea内的red box的大小。 基本上是文本的维度,而不是文本区域的维度。

HTML代码就是这样:

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

有没有办法实现这一点,使用Angular4 +或Javascript?

编辑:

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

 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,如:

 <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)
   }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM