textarea文本域html中常见的常用的表单元素之一,很多人被文本域的默认高度折磨的没有脾气,为什么这么说?我就是被气鼓鼓的人!(这里仅适合web页面的文本域,其他环境下有不同方案,例如微信小程序端:)

textarea用途分析

场景一:
默认的textarea文本域需要设置宽高或者行列数,这样实现的文本域才是正常的体现!

场景二:

另一种情况就是:文本域自动高度了,例如:qq输入框,微博输入框,都会跟着内容自动适应高度,而不是像场景一那样直接写死高度!怎么办?如何实现?

【已解决】关于textarea文本域自动高度问题方案整理!-Qui-Note

textarea文本域自动高度

关于这个textarea文本域自动高度的问题,在网上整理到两类可行方法:

方法一:文本域变div,div加contenteditable="true" 属性,用div造一个文本域出来,直接抛弃了textarea。

代码如下:

<style type="text/css">
.textarea{
    width: 500px;
    min-height: 20px;
    max-height: 300px;
    _height: 120px;
    margin:0 auto;
    padding: 2px;
    outline: 0; 
    font-size: 14px;
    line-height: 24px;
    word-wrap: break-word;
    overflow-x: hidden;
    overflow-y: auto; 
    border: 1px solid #000; 
}
</style>
<div class="textarea" contenteditable="true"><br /></div>

在线预览效果:https://course.51qux.com/textarea1

方案二:js动态监听textarea变化做出对应的调整,网上的js也有很多,我整理了兼容性和效果都差不多3个插件
css代码:

<style type="text/css">
textarea{
display: block;
width: 500px;
height: auto;
margin:0 auto;
    overflow: hidden; 
    font-size: 14px;
    height: 18px;
    line-height: 24px;
    padding:2px;
}
</style>

html代码:

<textarea id="textarea"></textarea>

js代码一:

<script type="text/javascript">
function autoHeight(el) {
    var timer = null;
    //由于ie8有溢出堆栈问题,故调整了这里
    var setStyle = function(el, auto) {
        if (auto) el.style.height = 'auto';
        el.style.height = el.scrollHeight + 'px';
    }
    var delayedResize = function(el) {
        if (timer) {
            clearTimeout(timer);
            timer = null;
        }
        timer = setTimeout(function() {
            setStyle(el)
        }, 200);
    }
    if (el.addEventListener) {
        el.addEventListener('input', function() {
            setStyle(el, 1);
        }, false);
        setStyle(el)
    } else if (el.attachEvent) {
        el.attachEvent('onpropertychange', function() {
            setStyle(el)
        })
        setStyle(el)
    }
    if (window.VBArray && window.addEventListener) { //IE9
        el.attachEvent("onkeydown", function() {
            var key = window.event.keyCode;
            if (key == 8 || key == 46) delayedResize(el);

        });
        el.attachEvent("oncut", function() {
            delayedResize(el);
        }); //处理粘贴
    }
}

var textarea = document.getElementById('textarea');
autoHeight(textarea);
</script>

js代码二:

<script type="text/javascript">
var autoTextarea = function (elem, extra, maxHeight) {
        extra = extra || 0;
        var isFirefox = !!document.getBoxObjectFor || 'mozInnerScreenX' in window,
        isOpera = !!window.opera && !!window.opera.toString().indexOf('Opera'),
                addEvent = function (type, callback) {
                        elem.addEventListener ?
                                elem.addEventListener(type, callback, false) :
                                elem.attachEvent('on' + type, callback);
                },
                getStyle = elem.currentStyle ? function (name) {
                        var val = elem.currentStyle[name];
 
                        if (name === 'height' && val.search(/px/i) !== 1) {
                                var rect = elem.getBoundingClientRect();
                                return rect.bottom - rect.top -
                                        parseFloat(getStyle('paddingTop')) -
                                        parseFloat(getStyle('paddingBottom')) + 'px';        
                        };
 
                        return val;
                } : function (name) {
                                return getComputedStyle(elem, null)[name];
                },
                minHeight = parseFloat(getStyle('height'));
 
        elem.style.resize = 'none';
 
        var change = function () {
                var scrollTop, height,
                        padding = 0,
                        style = elem.style;
 
                if (elem._length === elem.value.length) return;
                elem._length = elem.value.length;
 
                if (!isFirefox && !isOpera) {
                        padding = parseInt(getStyle('paddingTop')) + parseInt(getStyle('paddingBottom'));
                };
                scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
 
                elem.style.height = minHeight + 'px';
                if (elem.scrollHeight > minHeight) {
                        if (maxHeight && elem.scrollHeight > maxHeight) {
                                height = maxHeight - padding;
                                style.overflowY = 'auto';
                        } else {
                                height = elem.scrollHeight - padding;
                                style.overflowY = 'hidden';
                        };
                        style.height = height + extra + 'px';
                        scrollTop += parseInt(style.height) - elem.currHeight;
                        document.body.scrollTop = scrollTop;
                        document.documentElement.scrollTop = scrollTop;
                        elem.currHeight = parseInt(style.height);
                };
        };
 
        addEvent('propertychange', change);
        addEvent('input', change);
        addEvent('focus', change);
        change();
};

var text = document.getElementById("textarea");
autoTextarea(text);
</script>

js代码三:

<script type="text/javascript">
$(function(){
    $.fn.autoHeight = function(){    
       function autoHeight(elem){
           elem.style.height = 'auto';
           elem.scrollTop = 0; //防抖动
           elem.style.height = elem.scrollHeight + 'px';
       }
       this.each(function(){
           autoHeight(this);
           $(this).on('keyup', function(){
               autoHeight(this);
           });
       });     
   }         
   $('#textarea').autoHeight(); 
})
</script>

三种js方法都可以实现功能,选择其一就能解决问题!!!

JS效果预览地址:https://course.51qux.com/textarea2

这样就实现了html5中textarea文本域自动高度的问题,听起来就很牛逼,哈哈!又get一个技能,纸上得来终觉浅,绝知此事要躬行,加油打工人,奥利给!