如何获取文本区域内文本的高度 [英] How to get the height of the text inside of a textarea
问题描述
我有 textarea
,文字 Hello World
。我想得到这篇文章的高度。
I have a textarea
with the the text Hello World
. I would like to get the height of this text.
我试图使用:
var element = document.getElementById('textarea');
var textHeight = element.innerHTML.offsetHeight;
和:
var textHeight = element.value.offsetHeight;
但是这些不会给出文本的数字,而是<$ c $的高度c> textarea 元素。
But these don't give the numbers of the text, but the height of the textarea
element.
推荐答案
创建一个span元素,将Span的innerHTML设置为Hello World 。$
获取span的offsetHeight。
Create a span element, set Span's innerHTML to "Hello World".
Get the span's offsetHeight.
var span = document.createElement("span");
span.innerHTML="Hello World"; //or whatever string you want.
span.offsetHeight // this is the answer
请注意你必须设置span的字体样式到textarea的字体样式。
note that you must set the span's font style to the textarea's font style.
你的例子永远不会有效,因为innerHTML和value都是字符串。 String不定义offsetWidth。
Your example will NEVER work because innerHTML and value are both strings. String doesn't define offsetWidth.
如果您希望获得textarea中所选文本的高度,请使用selectionStart / selectionEnd查找textarea的选定文本。
If you wish to get the height of selected text inside of a textarea, use selectionStart/selectionEnd to find the selected text of the textarea.
这篇关于如何获取文本区域内文本的高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!