用JS scrollHeight方法实现textarea输入高度自适应的方法

来源:互联网 发布:windows 10 iso bt 编辑:程序博客网 时间:2024/04/29 02:31

HTML源代码部分:


                        <textarea id="content" name="content" onkeyup="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" onkeyup="autosize('description'); checkSupply(3000,'description');" name="description" id="description" style="height: 114px; padding-top: 20px;"></textarea>

首先模拟一个DIV。获取textarea内容,实时赋值给这个DIV。取它的高度再将其高度给textareafunction 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});    }}

0 0