Is there anyway to have a textarea “autofit” height based on the content at page load?

前端 未结 13 1753
借酒劲吻你
借酒劲吻你 2020-12-15 17:46

Is there anyway through CSS or Javascript set the height of the textarea based on the content? I have a hardcoded height in my CSS but i wanted it to default so there is no

13条回答
  •  生来不讨喜
    2020-12-15 18:22

    Without plugins you could do something like

    $(document).ready(function(){
      elem=document.getElementById('#elemid');
      while(elem.clientHeight < elem.scrollHeight) {elem.height(elem.height()+10)}
    });
    

    Resizing the textarea while it does have a scrollbar (so elem.clientHeight < elem.scrollHeight). You can do it quite easily even without JQuery, in plain javascript.

    Didn't test the code, it's just the "concept".

    EDIT: Dumb me, it's much easier, no loops...

    if (elem.clientHeight < elem.scrollHeight) elem.style.height=elem.scrollHeight+"px";
    

提交回复
热议问题