Is there a way to get a textarea to stretch to fit its content without using PHP or JavaScript?

后端 未结 5 1172
再見小時候
再見小時候 2020-12-08 03:25

I am filling a textarea with content for the user to edit.

Is it possible to make it stretch to fit content with CSS (like overflow:show for a div)?

相关标签:
5条回答
  • 2020-12-08 03:59

    Here is a function that works with jQuery (for height only, not width):

    function setHeight(jq_in){
        jq_in.each(function(index, elem){
            // This line will work with pure Javascript (taken from NicB's answer):
            elem.style.height = elem.scrollHeight+'px'; 
        });
    }
    setHeight($('<put selector here>'));
    

    Note: The op asked for a solution that does not use Javascript, however this should be helpful to many people who come across this question.

    0 讨论(0)
  • 2020-12-08 04:09

    Another simple solution for dynamic textarea control.

    <!--JAVASCRIPT-->
    <script type="text/javascript">
    $('textarea').on('input', function () {
                this.style.height = "";
                this.style.height = this.scrollHeight + "px";
     });
    </script>

    0 讨论(0)
  • 2020-12-08 04:16

    one line only

    <textarea name="text" oninput='this.style.height = "";this.style.height = this.scrollHeight + "px"'></textarea>
    
    0 讨论(0)
  • 2020-12-08 04:21

    This is a very simple solution, but it works for me:

    <!--TEXT-AREA-->
    <textarea id="textBox1" name="content" TextMode="MultiLine" onkeyup="setHeight('textBox1');" onkeydown="setHeight('textBox1');">Hello World</textarea>
    
    <!--JAVASCRIPT-->
    <script type="text/javascript">
    function setHeight(fieldId){
        document.getElementById(fieldId).style.height = document.getElementById(fieldId).scrollHeight+'px';
    }
    setHeight('textBox1');
    </script>

    0 讨论(0)
  • 2020-12-08 04:22

    Not really. This is normally done using javascript.

    there is a good discussion of ways of doing this here...

    Autosizing textarea using Prototype

    0 讨论(0)
提交回复
热议问题