监听textarea输入文本变化,让textarea高度自增长

原本textarea只有一行高,随着输入字数的增多,默认增长,通常会用在移动端产品输入上

使用oninput比onkeyup更适合手机端

<textarea id="txtContent" class="j_comment_in comment-input" rows="1" oninput="ResizeTextarea('txtContent')" style="overflow-y:hidden;" placeholder="我也说一句..."></textarea> 
//最小高度 
var minRows = 1; 
// 最大高度,超过则出现滚动条 
var maxRows = 6; 
function ResizeTextarea(id){ 
    var t = document.getElementById(id); 
    if (t.scrollTop == 0) t.scrollTop=1; 
    while (t.scrollTop == 0){ 
        if (t.rows > minRows) 
            t.rows--; 
        else 
            break; 
        t.scrollTop = 1; 
        if (t.rows < maxRows) 
            t.style.overflowY = "hidden"; 
        if (t.scrollTop > 0){ 
            t.rows++; 
            break; 
        } 
    } 
    while(t.scrollTop > 0){     
        if (t.rows < maxRows){ 
            t.rows++; 
            if (t.scrollTop == 0) t.scrollTop=1; 
        } 
        else{ 
            t.style.overflowY = "auto"; 
            break; 
        } 
    } 
} 

 js监听的写法

document.getElementById("txtContent").addEventListener("input", ResizeTextarea, false);

 

转载于:https://www.cnblogs.com/snowbaby-kang/p/4887400.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值