您的位置:首页 > 其它

textarea 高度自适应

2017-05-13 05:10 337 查看
一、
$('textarea').keyup(function(){
$(this).height(this.scrollHeight);
});
效果一般

二、https://github.com/alexdunphy/flexText
<divclass="flex-text-wrap">
  <pre>
    <span></span>
    <br>
    <br>
  </pre>
  <textareaid="content"placeholder="Type/paste/shoutcontent…"></textarea>
</div>


.flex-text-wrap{
position:relative;

*zoom:1;
}

textarea,
.flex-text-wrap{
outline:0;
margin:0;
border:none;
padding:0;

*padding-bottom:0!important;
}

.flex-text-wraptextarea,
.flex-text-wrappre{
white-space:pre-wrap;
width:100%;
-webkit-box-sizing:border-box;
-moz-box-sizing:border-box;
box-sizing:border-box;

*white-space:pre;
*word-wrap:break-word;
}

.flex-text-wraptextarea{
overflow:hidden;
position:absolute;
top:0;
left:0;
height:100%;
width:100%;
resize:none;

/*IE7box-sizingfudgefactor*/
*height:94%;
*width:94%;
}

.flex-text-wrappre{
display:block;
visibility:hidden;
}

textarea,
.flex-text-wrappre{
/*
*Addcustomstylinghere
*Ensurethattypography,padding,border-width(andoptionallymin-height)areidenticalacrosstextarea&pre
*/
}


;(function($){

//Constructor
functionFT(elem){
this.$textarea=$(elem);

this._init();
}

FT.prototype={
_init:function(){
var_this=this;

//Insertwrapperelem&pre/spanfortextareamirroring
this.$textarea.wrap('<divclass="flex-text-wrap"/>').before('<pre><span/><br/><br/></pre>');

this.$span=this.$textarea.prev().find('span');

//Addinputeventlisteners
//*inputformodernbrowsers
//*propertychangeforIE7&8
//*keyupforIE>=9:catcheskeyboard-triggeredundos/cuts/deletes
//*changeforIE>=9:catchesmouse-triggeredundos/cuts/deletions(whentextarealosesfocus)
this.$textarea.on('inputpropertychangekeyupchange',function(){
_this._mirror();
});

//jQueryval()stripscarriagereturncharsbydefault(seehttp://api.jquery.com/val/)//ThiscausesissuesinIE7,butavalHookcanbeusedtopreservethesechars
$.valHooks.textarea={
get:function(elem){
returnelem.value.replace(/\r?\n/g,"\r\n");
}
};

//Mirrorcontentsonceoninit
this._mirror();
}

//Mirrorpre/span&textareacontents
,_mirror:function(){
this.$span.text(this.$textarea.val());
}
};

//jQuerypluginwrapper
$.fn.flexText=function(){
returnthis.each(function(){
//Checkifalreadyinstantiatedonthiselem
if(!$.data(this,'flexText')){
//Instantiate&storeelem+string
$.data(this,'flexText',newFT(this));
}
});
};

})(jQuery);


调用:

$(function(){
$('textarea').flexText();
});



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: