3个知识点:
1.事件触发,onpropertychange for ie,oninput for ff (http://www.cnblogs.com/bravfing/archive/2012/04/10/2440681.html)。
2.通过scrollHeight得到内容实际高度然后赋值给height。
3.过程2里有个问题,for ff的,是因为ff对scrollHeight的解释是大于等于clientHeight的,所以当文本行数变少的时候,scollHeight不能得到真实值,这里有个小技巧,就是先赋给height一个最小值就可以了。
最后,如果textarea是百分比宽度的,当window resize的时候,要主动触发赋值事件。代码如下:
var auto = function(el){ var min = el.height(),ev_name; // for ie if(ie){ ev_name = "propertychange"; } // for other else{ ev_name = "input"; } el.on(ev_name,function(ev){ if(!ie)el.height(min); el.height(Math.max(this.scrollHeight,min)); }); // window resize时候主动触发 $(window).on("resize",function(){ el.trigger(ev_name); }); }; auto($("#to"));