How can I make a <textarea>
auto-resize with its content (like in Facebook) using jQuery.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
Use jQuery UI
Check this demo: http://jqueryui.com/demos/resizable/#textarea
回答2:
<script type="text/javascript">
function adjustTextarea(this_){
var value_ = this_.value;
value_ = value_.replace(new RegExp("\n\r", 'gi'), "\n");
value_ = value_.replace(new RegExp("\r", 'gi'), "\n");
var split_ = value_.split("\n");
this_.rows = split_.length;
return;
}
</script>
<textarea cols="100" style="overflow:hidden;" onkeyup="adjustTextarea(this);" onfocus="adjustTextarea(this);" >
Text
</textarea>
回答3:
Use James Padolsey autoResize jquery plugin from http://james.padolsey.com/javascript/jquery-plugin-autoresize/
Basic usage
$('textarea#comment').autoResize({
// On resize:
onResize : function() {
$(this).css({opacity:0.8});
},
// After resize:
animateCallback : function() {
$(this).css({opacity:1});
},
// Quite slow animation:
animateDuration : 300,
// More extra space:
extraSpace : 40
});
回答4:
Super light weight:
Has anyone considered contenteditable? No messing around with scrolling,a nd the only JS I like about it is if you plan on saving the data on blur... and apparently, it's compatible on all of the popular browsers : http://caniuse.com/#feat=contenteditable
Just style it to look like a text box, and it autosizes... Make its min-height the preferred text height and have at it.
What's cool about this approach is that you can save and tags on some of the browsers.
http://jsfiddle.net/gbutiri/v31o8xfo/
<style>
.autoheight {
min-height: 16px;
font-size: 16px;
margin: 0;
padding: 10px;
font-family: Arial;
line-height: 16px;
box-sizing: border-box;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
overflow: hidden;
resize: none;
border: 1px solid #ccc;
outline: none;
width: 200px;
}
</style>
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script>
$(document).on('blur','.autoheight',function(e) {
var $this = $(this);
// The text is here. Do whatever you want with it.
console.log($this.html());
});
</script>
<div class="autoheight contenteditable" contenteditable="true">Mickey <b>Mouse</b></div>