监听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);

 

posted @ 2015-10-17 13:56  雪宝贝_kang  阅读(1821)  评论(0编辑  收藏  举报