how to expand a text area when click on

后端 未结 9 1288
感情败类
感情败类 2021-02-02 10:17

Im working on a small project which has a textarea and i need help in making the text area expand on mouse click like that of twitter and facebook. the textarea should look lik

相关标签:
9条回答
  • 2021-02-02 10:21

    This can be done without the use of JavaScript/jQuery, using CSS transitions.

    textarea {
        height: 1em;
        width: 50%;
        padding: 3px;
        transition: all 0.5s ease;
    }
    
    textarea:focus {
        height: 4em;
    }
    <textarea rows="1" cols="10"></textarea>

    0 讨论(0)
  • 2021-02-02 10:33

    use this plugin > http://plugins.jquery.com/project/elastic

    very simple and effective !

    0 讨论(0)
  • 2021-02-02 10:33

    You can do this with CSS only using position: absolute, which will make it float over other elements, and the :focus selector, which will be applied only when the element have the focus. First you need to reserve the textarea size enclosing it in an element:

    <div class="textarea"><textarea></textarea></div>
    
    div.textarea {
       height: 50px;
       width: 400px;
    }
    

    Then style the unfocused textarea

    textarea {
       position: absolute;
       height: 50px;
       width: 400px;
       transition: all 200ms;
    }
    

    And finally the focused one

    textarea:focus {
       z-index: 1001;
       min-height:250px;
    }
    

    Fiddle: http://jsfiddle.net/7v60su9e/

    0 讨论(0)
  • 2021-02-02 10:35

    This will work for you:

    <textarea rows="1" cols="40" onfocus="this.rows=10;" style="resize: none;">Tweet Tweet....</textarea>
    

    I used onfocus instead of onclick because onclick isn't fired if the user uses the tab key to move to the textarea. You'll also want to make sure the user can't resize it themselves - hence the style attribute.

    You could also add onblur="this.rows=1;" to shrink it back down once the user moves out of your textarea.

    0 讨论(0)
  • 2021-02-02 10:38

    You can do something like below:

    <textarea name="textBox" rows="1" cols="20" id="textBox" onfocus="document.getElementById('textBox').rows = 5;" >
    
    0 讨论(0)
  • 2021-02-02 10:41

    Based in doog abides comment using jQuery, I enhanced the code to autoadjust approximately the number of rows acording to the length of the content, and return to 1 when focus is lost.

    HTML:

    <textarea class="expand" rows="1" cols="10"></textarea>
    

    jQuery:

    $('textarea.expand').focus(function () {
        $(this).animate({rows: Math.max(1,Math.ceil($(this).val().length/this.cols))}, 500);
    });
    $('textarea.expand').blur(function () {
        $(this).animate({rows: 1}, 500);
        //Resize back to one row if the textarea is manually resized via the handle
        $(this).css({height: ''});
        $(this).css({width: ''});
    });
    
    0 讨论(0)
提交回复
热议问题