![](/img/trans.png)
[英]How to get text width inside textarea? (javascript/jquery)
[英]How to get text width and height inside a TextArea in HTML using 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.