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

标签 javascript html angular

有这样的场景:

Sample out put

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

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 includes border width, clientWidth does not

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

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

如果您想在 angular 组件代码中获取宽度:

一些组件.html:

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

一些组件.ts:

export class SystemComponent implements OnInit {

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

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

关于javascript - 如何使用 JavaScript 获取 HTML 中 TextArea 内的文本宽度和高度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52888529/

相关文章:

c# - 在 div 中显示用户名列表

java - 支持 Javascript 和 CSS 的 JEditorPane

html - 通过 CSS 的多 div 水平选取框

html - CSS 按钮不会在 div 中心对齐

express - 前端和后端的不同端口。如何提出要求?

javascript - Array.prototype.map.bind 与对象一起使用是否可靠?

javascript - 使用 ionic angularjs 创建 cookie 并将 cookie 保留很长时间

javascript - en-IN 区域设置不适用于 Angular 货币管道

angular - http ://localhost:4200 from windows is working with ng serve from WSL2, 怎么来的?

javascript - 如何在 Angular 中将列表项分离为组件