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

后端 未结 8 1632
眼角桃花
眼角桃花 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:42

    You can use element.scrollHeight (just like Patrick answered) but it needs some corrections (I'm using jQuery in example):

    1) if your textarea has padding, you need to substract it (top & bottom).

    2) if element has already set height, you need to set it to zero (just for measure then set it back, else it returns this height + padding)

    var h0 = $(element).height();  // backup height
    $(this).height(0); 
    var h = $(this).get(0).scrollHeight - $(this).css('paddingTop').replace('px','')*1 - $(this).css('paddingBottom').replace('px','')*1; // actual text height
    $(this).height(h0); // set back original height (or new height using h)
    

    There is no need of extra span with same css as textarea.

提交回复
热议问题