Auto expand a textarea using jQuery

2019-01-02 14:39发布

How can I make a textarea automatically expand using jQuery?

I have a textbox for explaining the agenda of the meeting, so I want to expand that textbox when my agenda's text keep growing that textbox area.

标签: jquery
27条回答
旧时光的记忆
2楼-- · 2019-01-02 15:27

There is also the very cool bgrins/ExpandingTextareas (github) project, based on a publication by Neill Jenkins called Expanding Text Areas Made Elegant

查看更多
听够珍惜
3楼-- · 2019-01-02 15:28

I fixed a few bugs in the answer provided by Reigel (the accepted answer):

  1. The order in which html entities are replaced now don't cause unexpected code in the shadow element. (The original replaced ">" by "&ampgt;", causing wrong calculation of height in some rare cases).
  2. If the text ends with a newline, the shadow now gets an extra character "#", instead of having a fixed added height, as is the case in the original.
  3. Resizing the textarea after initialisation does update the width of the shadow.
  4. added word-wrap: break-word for shadow, so it breaks the same as a textarea (forcing breaks for very long words)

There are some remaining issues concerning spaces. I don't see a solution for double spaces, they are displayed as single spaces in the shadow (html rendering). This cannot be soved by using  , because the spaces should break. Also, the textarea breaks a line after a space, if there is no room for that space it will break the line at an earlier point. Suggestions are welcome.

Corrected code:

(function ($) {
    $.fn.autogrow = function (options) {
        var $this, minHeight, lineHeight, shadow, update;
        this.filter('textarea').each(function () {
            $this = $(this);
            minHeight = $this.height();
            lineHeight = $this.css('lineHeight');
            $this.css('overflow','hidden');
            shadow = $('<div></div>').css({
                position: 'absolute',
                'word-wrap': 'break-word',
                top: -10000,
                left: -10000,
                width: $this.width(),
                fontSize: $this.css('fontSize'),
                fontFamily: $this.css('fontFamily'),
                lineHeight: $this.css('lineHeight'),
                resize: 'none'
            }).appendTo(document.body);
            update = function () {
                shadow.css('width', $(this).width());
                var val = this.value.replace(/&/g, '&amp;')
                                    .replace(/</g, '&lt;')
                                    .replace(/>/g, '&gt;')
                                    .replace(/\n/g, '<br/>')
                                    .replace(/\s/g,'&nbsp;');
                if (val.indexOf('<br/>', val.length - 5) !== -1) { val += '#'; }
                shadow.html(val);
                $(this).css('height', Math.max(shadow.height(), minHeight));
            };
            $this.change(update).keyup(update).keydown(update);
            update.apply(this);
        });
        return this;
    };
}(jQuery));
查看更多
零度萤火
4楼-- · 2019-01-02 15:28

Code of SpYk3HH with addition for shrinking size.

function get_height(elt) {
    return elt.scrollHeight + parseFloat($(elt).css("borderTopWidth")) + parseFloat($(elt).css("borderBottomWidth"));
}

$("textarea").keyup(function(e) {
    var found = 0;
    while (!found) {
        $(this).height($(this).height() - 10);
        while($(this).outerHeight() < get_height(this)) {
            $(this).height($(this).height() + 1);
            found = 1;
        };
    }
});
查看更多
姐姐魅力值爆表
5楼-- · 2019-01-02 15:28

The simplest solution:

html:

<textarea class="auto-expand"></textarea>

css:

.auto-expand {
    overflow:hidden;
    min-height: 80px;
}

js (jquery):

$(document).ready(function () {
 $("textarea.auto-expand").focus(function () {
        var $minHeight = $(this).css('min-height');
        $(this).on('input', function (e) {
            $(this).css('height', $minHeight);
            var $newHeight = $(this)[0].scrollHeight;
            $(this).css('height', $newHeight);
        });
    });       
});
查看更多
浅入江南
6楼-- · 2019-01-02 15:29

Solution with pure JS

function autoSize() {
  if (element) {
    element.setAttribute('rows', 2) // minimum rows
    const rowsRequired = parseInt(
      (element.scrollHeight - TEXTAREA_CONFIG.PADDING) / TEXTAREA_CONFIG.LINE_HEIGHT
    )
    if (rowsRequired !== parseInt(element.getAttribute('rows'))) {
      element.setAttribute('rows', rowsRequired)
    }
  }
}

https://jsfiddle.net/Samb102/cjqa2kf4/54/

查看更多
查无此人
7楼-- · 2019-01-02 15:30

Everyone should try this jQuery plugin: xautoresize-jquery. It's really good and should solve your problem.

查看更多
登录 后发表回答