有时候希望textarea 能够自动调整高度来适应输入的内容

网上看到了很多解决方案,比如动态创建一个隐藏的div,当用户输入的时候将textarea的内容绑定到div,由于div的高度会自动撑开,因此可以动态检测div的高度,然后将div的高度复制给textarea。这个方法应该是兼容性较好而且比较稳健的办法,但实在太繁琐

还有一个解决办法就是动态将textarea的scrollHeight 复制给高度。我采用的是后者

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
var textarea = document.getElementById('textarea');
// hide scroll bar
textarea.style.overflow = 'hidden';
var height = parseInt(window.getComputedStyle(textarea).height);
var width = parseInt(window.getComputedStyle(textarea).width);
var autoHeight = function() {
if(this.scrollHeight <= height || this.value == '') {
this.style.height=height + 'px';
return;
}
this.style.height = this.scrollHeight + 'px';
}
textarea.oninput = autoHeight;
var textarea = document.getElementById('textarea'); // hide scroll bar textarea.style.overflow = 'hidden'; var height = parseInt(window.getComputedStyle(textarea).height); var width = parseInt(window.getComputedStyle(textarea).width); var autoHeight = function() { if(this.scrollHeight <= height || this.value == '') { this.style.height=height + 'px'; return; } this.style.height = this.scrollHeight + 'px'; } textarea.oninput = autoHeight;
var textarea = document.getElementById('textarea');
    // hide scroll bar
textarea.style.overflow = 'hidden';
var height = parseInt(window.getComputedStyle(textarea).height);
var width = parseInt(window.getComputedStyle(textarea).width);
var autoHeight = function() {
    if(this.scrollHeight <= height || this.value == '') {
        this.style.height=height + 'px';
        return;
    }
    this.style.height = this.scrollHeight +  'px';
}
textarea.oninput = autoHeight;

这个方法就是通过监听textarea的oninput 来实现,也可以监听keyup,keydown;但是如果使用keyup或者keydown来监听的话会存在一个问题,那就是如果textarea有复制或者剪切操作,keyup,keydown不会立即响应内容的变化,并且也不能响应鼠标右键粘贴。

最后再象征性地增加兼容

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
textarea.onpropertychange = function (event) {
if(event.propertyName.toLowerCase() == 'value') {
autoHeight();
console.log(this.value);
}
}
textarea.onpropertychange = function (event) { if(event.propertyName.toLowerCase() == 'value') { autoHeight(); console.log(this.value); } }
textarea.onpropertychange = function (event) {
    if(event.propertyName.toLowerCase() == 'value') {
        autoHeight();
        console.log(this.value);
    }
}

然而悲伤的是这种方式并不适用移动端,移动端所有浏览器均测试无效

另外还有一个解决办法就是不使用textarea,而是使用普通div模拟textarea,因为div本身高度就自动增长,所有就不用担心其他问题了。实现方式就是给div设置属性

contentEditable=true
contentEditable=true,这样div就变为可编辑的了。不过这种方式在某些firefox上面,div外层会出现虚框,从而使得div的本质暴露无疑。解决办法就是css配置
outline:0 none
outline:0 none