Textarea 高度自适应 根据内容自适应高度

<body>
    <form id="form1" runat="server">
    <div>
    <textarea id='textarea' name="textarea" onpropertychange='setTareaAutoHeight("textarea")' oninput='setTareaAutoHeight("textarea")' style="width:100%; overflow-y:hidden; border:0; font-size:12px"><asp:Literal ID="litCont" runat="server"></asp:Literal></textarea>
    <!--
IE支持 onPropertyChange 火狐支持oninput

Firefox有个oninput事件效果和onPropertyChange一样,所以同时加上oninput和onPropertyChange问题就解决
-->

    </div>
    </form>
</body>
  function init() {
        // 设置textarea自适应高度
        var handler = function () {
            setTareaAutoHeight('textarea');
        };

        // 添加监听
        if (window.addEventListener) {//FF
            window.addEventListener('DOMContentLoaded', handler, false);
            window.addEventListener('load', handler, false);
        } else if (window.attachEvent)//IE
            window.attachEvent('onload', handler);
        else
            window.onload = handler;
    } // end init

    init();

    function setTareaAutoHeight(id) {
        document.getElementById(id).style.height = document.getElementById(id).scrollHeight + "px";
    }

posted @ 2012-01-10 11:35  顿金  阅读(714)  评论(0编辑  收藏  举报