场景需求:根据输入内容自适应高度,textarea不能满足需求,需要该进
autoTextarea.js:
define('autoTextarea',[],function(){
return{
/*
* 文本框根据输入内容自适应高度
*cfg{ //配置参数
elem:elem,//输入元素
extra:extra,// 设置光标与输入框保持的距离(默认0)
maxHeight:maxHeight,//设置最大高度(可选)
initEvent:initEvent, //是否初始化文本高度(true / false)
initScroll:initScroll,//是否初始化文本框滚回顶部(true/false)
changeHeight:changeHeight // 回调函数
}
*/
fn:function(cfg){
if(!cfg){return}
var elem=cfg.elem,extra=cfg.extra||0,maxHeight=cfg.maxHeight||0,initEvent=cfg.initEvent||false,initScroll=cfg.initScroll||false;
var addEvent=function(type,callback){
elem.addEventListener?elem.addEventListener(type,callback,false):elem.attachEvent('on'+type,callback);
};
var getStyle;
if(elem.currentStyle){
getStyle=function(name){
var val=elem.currentStyle[name];
if(name==='height'&&val.search(/px/i) !==1){
var rect=elem.getBoundingClientRect();
return rect.bottom-rect.top-parseFloat(getStyle('paddingTop'))-parseFloat(getStyle('paddingBottom'))+'px'
}
return val;
};
}else{
getStyle=function(name){
return getComputedStyle(elem,null)[name];
};
}
var minHeight=parseFloat(getStyle('height'))>=0?parseFloat(getStyle('height')):0;
elem.style=resize='none';//如果不希望使用这可以自由的伸展textarea的高度可以设置其他值
var change=function(type){
var height;
var style=elem.style;
if(elem._length===elem.value.length) return;
elem._length=elem.value.length;
var scrollTop=document.body.scrollTop||document.documentElement.scrollTop;
elem.style.height=minHeight+'px';
if(elem.scrollHeight>=minHeight){
if(maxHeight&&elem.scrollHeight>maxHeight){
height=maxHeight;
style.overflowY='auto';
}else{
height=elem.scrollHeight;
style.overflowY='hidden';
}
style.height=height+extra+'px';
if(initScroll){
scrollTop+=parseInt(style.height)-elem.currHeight;
document.body.scrollTop=scrollTop;
document.documentElement.scrollTop=scrollTop;
}
elem.currHeight=parseInt(style.height);
if(cfg&&typeof cfg.changeHeight==='function'){cfg.changeHeight(height+extra)}
if(type=='keydown'||type=='input'){elem.focus()}
}
} ;
if(initEvent){change();}
addEvent('focus',function(){change('focus')});
addEvent('input',function(){change('input')}) ;
}
}
});
调用如下:
<textarea name='conten' row='1' class='simulation-textarea validate ipt' type='text'>
输入内容区,高度回随内容的高度变化,不会出现滚动条
</textarea>
引入autoTextarea.js
require(['auto Textarea'],function(autoTextareaUtils)){
var autoTextarea=autoTextareaUtils.fn;
autoTextarea({elem:$('.simulation-textarea')[0],initEvent:false})
})
几乎兼容所有主流浏览器,IE可以兼容到IE8