第2521天:textarea根据内容自适应高度

来源:http://www.jb51.net/article/42468.htm

var observe;
if (window.attachEvent) {
    observe = function (element, event, handler) {
        element.attachEvent('on'+event, handler);
    };
} else {
    observe = function (element, event, handler) {
        element.addEventListener(event, handler, false);
    };
}
function autoTextarea (elem) {
    var text = document.getElementById(elem);
    function resize () {
        text.style.height = 'auto';
        text.style.height = text.scrollHeight+'px';
    }
    /* 0-timeout to get the already changed text */
    function delayedResize () {
        window.setTimeout(resize, 0);
    }
    observe(text, 'change',  resize);
    observe(text, 'cut',     delayedResize);
    observe(text, 'paste',   delayedResize);
    observe(text, 'drop',    delayedResize);
    observe(text, 'keydown', delayedResize);
    text.focus();
    text.select();
    resize();
}

// 调用
autoTextarea('myTextareaId');

 

RSS

上一篇:

下一篇:

发表评论

电子邮件地址不会被公开。 必填项已用*标注