现在的位置: 首页 > 综合 > 正文

【记录】用Javascript实现文本框textarea高度随内容自动适应增长收缩

2012年06月27日 ⁄ 综合 ⁄ 共 1247字 ⁄ 字号 评论关闭

 // 最小高度

    var minRows = 5;
    
// 最大高度,超过则出现滚动条
    var maxRows = 12;
    
function autoResize(){
        
var t = document.getElementById('txt');
        
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;
            }
        }
    }

查看DEMO-示例

抱歉!评论已关闭.