如何获取文本区域内文本的高度

编程入门 行业动态 更新时间:2024-10-27 16:35:59
本文介绍了如何获取文本区域内文本的高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有 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;

但是这些不会给出文本的数字,而是 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.

更多推荐

如何获取文本区域内文本的高度

本文发布于:2023-11-10 00:29:39,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1573860.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文本   区域内   高度

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!