HTML源代码部分:
<textarea id="content" name="content" οnkeyup="autosize(this); checkSupply(4000,'content');" default_height="94">{$answer['content']}</textarea>
/*html中focus函数也经过测试不好使。*/
//textarea高度自适应
function autosize(obj) {var d_h = parseInt(obj.attributes['default_height'].value);
if(obj.scrollHeight > d_h) {
alert(obj.scrollHeight);
obj.style.height = obj.scrollHeight + 'px';
} else {
obj.style.height = d_h + 'px';
}
}
这个方法适应FF。
但有一个BUG。在IE浏览器下面,scrollHeight值有偏差它的scrollHeight
会莫名奇妙地多出一些,看起来非常奇怪。。
一直在网上寻找解决方案无果。
最后经一位大神提醒,修改了一下解决方案。。
首先模拟一个DIV。获取textarea内容,实时赋值给这个DIV。然后取它的高度再将其高度给textarea
html部分:
<textarea default_height="94" οnkeyup="autosize('description'); checkSupply(3000,'description');" name="description" id="description" style="height: 114px; padding-top: 20px;"></textarea>
首先模拟一个DIV。获取textarea内容,实时赋值给这个DIV。取它的高度再将其高度给textarea function autosize(obj) { var d_h = parseInt($('#'+obj).attr('default_height')); var mnDiv ='<div class="mnDiv"></div>'; $('.mnDiv').remove(); $('#'+obj).after(mnDiv); $('.mnDiv').css({width:$('#'+obj).width(),display:"none"}).html('<pre>'+$('#'+obj).val()+'</pre>');//填充内容 var mnDivHeight =$('.mnDiv').height(); if(mnDivHeight > d_h) { // alert($('#'+obj)[0].scrollHeight); $('#'+obj).css({'height':mnDivHeight,'padding-top':'20px'}); } else { $('#'+obj).css({'height':d_h}); } }