textarea高度随文本内容变化,且不出现滚动条

通常文本域的写法如下

<textarea type="text" class="form-control pull-left" id="description" name="description"></textarea>

在页面的显示效果如下

一般会有一个初始高度,当不对该文本域进行处理,文本域的高度不会发生变化,当文本域内的内容过多时,将会出现滚动条,效果如下

效果不美观。

现在想让文本域的高度随内容的多少而发生改变,且不会产生滚动条。

可以使用以下代码

$('textarea').each(function () {
        this.setAttribute('style', 'height:' + (this.scrollHeight) + 'px;overflow-y:hidden;');
    }).on('input', function () {
        this.style.height = 'auto';
        this.style.height = (this.scrollHeight) + 'px';
    });

显示效果如下

该文本域的高度会随着内容的增多而变大,也会随着内容的减少而减小。实时变化。

 

有时候情况会比较复杂,例如我在做一个项目,前台使用的是bootstrap,使用model模态框弹出一个页面,在页面上有一个文本域,保持原本的代码保持不变,效果就发生了变化。

我猜想这种效果的出现可能是因为弹出框的高度和宽度问题。

后来改了一下代码,首先给文本域一个默认高度

<textarea type="text" class="form-control pull-left" id="description" name="description" style="height: 50px"></textarea>

文本域得到焦点后,再实时监控文本域里的内容,然后让高度随之变化。

$("#description").focus(function () {
        $('textarea').each(function () {
            this.setAttribute('style', 'height:' + (this.scrollHeight) + 'px;overflow-y:hidden;');
        }).on('input', function () {
            this.style.height = 'auto';
            this.style.height = (this.scrollHeight) + 'px';
        });
    });

 

posted @ 2018-09-19 16:25  ____Peanut  阅读(3356)  评论(0编辑  收藏  举报