有这样的场景:
需要获取文本区域内红框
的大小。基本上是文本的尺寸,而不是文本区域的尺寸。
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/