如何更改具有className的textarea的动态高度?

时间:2015-04-06 11:58:49

标签: javascript height textarea

我试图自动修改有id的textarea。 使用此代码,

function init () {
var text = document.getElementById('id1');
function resize () {
    var clone = text.cloneNode();
    clone.className = 'clone';
    text.parentNode.insertBefore(clone, text);
    clone.style.height = 'auto';
    clone.value = text.value;
    text.style.height = (clone.scrollTop + clone.scrollHeight -20) + 'px';
    text.parentNode.removeChild(clone);
}
/* 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();
}

我通过getElementsByClassName更改了getElementByID。然后克隆它,但它不起作用。

 var chs = document.getElementsByClassName("ch");
 for(var k  = 0; k < chs.length;k++){
             function resize () {
                var clone = chs[k].cloneNode();
                clone.className = 'clone';
                chs[k].parentNode.insertBefore(clone, chs[k]);
                clone.style.height = 'auto';
                clone.value = chs[k].value;
                chs[k].style.height = (clone.scrollTop + clone.scrollHeight -20) + 'px';
                chs[k].parentNode.removeChild(clone);
            }
            function delayedResize () {
                window.setTimeout(resize, 0);
            }
            observe(chs[k], 'change',  resize);
            observe(chs[k], 'cut',     delayedResize);
            observe(chs[k], 'paste',   delayedResize);
            observe(chs[k], 'drop',    delayedResize);
            observe(chs[k], 'keydown', delayedResize);
            chs[k].focus();
            chs[k].select();
            resize();
    }

错误是Uncaught TypeError:无法读取属性&#39; cloneNode&#39; of undefinedindex.html:253 resize

我需要的是让所有textarea动态改变高度。像FB feed textarea。

0 个答案:

没有答案