html textarea文本域高度自适应

1、可直接在 菜鸟教程网站测试页面中测试

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
    <title>菜鸟教程(runoob.com)</title>
</head>
<body>
    <textarea style="width: 200px;padding:0px;"
          id="symptomTxt"
          oninput="autoTextAreaHeight(this)"
         >
    </textarea>
</body>
<script type="text/javascript">    
    //文本域自适应
     function autoTextAreaHeight(o) {
        o.style.height = o.scrollTop + o.scrollHeight + "px";
    } 
    $(function () {
        var ele = document.getElementById("symptomTxt");
        autoTextAreaHeight(ele);
    }) 
</script>
</html>

2、其实这个段代码有些小瑕疵,输入的时候,高度自适应,但是足字删除输入的内容时,高度就不自适应了

本人改进办法,由于时间仓促,可能不是很好,如果你有好的方式,可以告诉我,在这里谢谢了。

解决:因为文本域宽度200px,测试了下,每行能输入15个汉字,length长度为30。所以我监听输入的长度,当大于30时就追加文本域高度。

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
    <title>菜鸟教程(runoob.com)</title>
</head>
<body>
    <textarea style="width: 200px;padding:0px;"
          id="symptomTxt"
          oninput="autoTextAreaHeight(this)"
         >
    </textarea>
</body>
<script type="text/javascript">    
    //获取文本长度,一个汉字长度为2
    var strLength = {};
    strLength.GetLength = function(str) {
      return str.replace(/[\u0391-\uFFE5]/g,"aa").length;  //先把中文替换成两个字节的英文,在计算长度
    };
    //文本域自适应
     function autoTextAreaHeight(o) {
        var element = $(o).val();
        var len = strLength.GetLength(element);
        var rows = Math.ceil(len/30); 
        o.style.height = o.scrollTop + 30 + (rows>0?rows-1:rows)*10 + "px";
        //o.style.height = o.scrollTop + o.scrollHeight + "px";
    } 
    $(function () {
        var ele = document.getElementById("symptomTxt");
        autoTextAreaHeight(ele);
    }) 
</script>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值