How to get the height of the text inside of a textarea

后端 未结 8 1621
眼角桃花
眼角桃花 2020-12-05 10:02

I have a textarea with the the text Hello World. I would like to get the height of this text.

I\'ve tried to use:

var eleme         


        
8条回答
  •  不思量自难忘°
    2020-12-05 10:40

    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
    

    note that you must set the span's font style to the textarea's font style.

    Your example will NEVER work because innerHTML and value are both strings. String doesn't define offsetWidth.

    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.

提交回复
热议问题