MENU

jQuery - textarea 自适应内容高度

• September 15, 2019 • Read: 4279 • 代码分享,资源分享阅读设置

<textarea id="textarea"></textarea>
<script>
function makeExpandingArea(el) {
    var setStyle = function(el) {
        el.style.height = 'auto';
        el.style.height = el.scrollHeight + 'px';
        // console.log(el.scrollHeight);
    }
    var delayedResize = function(el) {
        window.setTimeout(function() {
            setStyle(el);
        },
        0);
    }
    if (el.addEventListener) {
        el.addEventListener('input',function() {
            setStyle(el);
        },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);
        }); //处理粘贴
    }
}
makeExpandingArea(textarea);
</script>
Last Modified: September 20, 2019
Archives QR Code Tip
QR Code for this page
Tipping QR Code
Leave a Comment

已有 1 条评论
  1. 觉得不好看可以自己进行美化,修改样式就行了