Textareaコンテンツに応じて高さを適応

2148 ワード

コードを直接見ましょう.簡単で、実用的です.
 
  



autoresizing textarea

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