jQuery自动增长插件扩展textarea以适应其内容。功能如下。
(function($) {
/*
* Auto-growing textareas; technique ripped from Facebook
*/
$.fn.autogrow = function(options) {
this.filter('textarea').each(function() {
var $this = $(this),
minHeight = $this.height(),
lineHeight = $this.css('lineHeight');
var shadow = $('<div></div>').css({
position: 'absolute',
top: -10000,
left: -10000,
width: $(this).width(),
fontSize: $this.css('fontSize'),
fontFamily: $this.css('fontFamily'),
lineHeight: $this.css('lineHeight'),
resize: 'none'
}).appendTo(document.body);
var update = function() {
var val = this.value.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/&/g, '&')
.replace(/\n/g, '<br/>');
shadow.html(val);
$(this).css('height', Math.max(shadow.height() + 20, minHeight));
}
$(this).change(update).keyup(update).keydown(update);
update.apply(this);
});
return this;
}
})(jQuery);
然后触发$('textarea').autogrow();
。在JQuery加载函数之后,我们加载一个新的textarea。因此我触发了这个。
$('.commentslogic').load(window.location.href + ' .commentslogic .inner', function(){
$('textarea').autogrow();
});
但它不适用于新的textarea,而且FireBug中没有报告错误。救命啊!
Fiddle dee dee Fiddle dee dum http://jsfiddle.net/JTmND/8/
答案 0 :(得分:2)
正如评论中所指出的,这个小提琴就是解决方案:http://jsfiddle.net/JTmND/11/
$(document).ready(function() {
$('textarea').autogrow();
$('.button').click(function() {
$('.test').html('<textarea></textarea>');
$('.test').find('textarea').autogrow();
});
});
如何将新的textareas添加到dom(手动或通过ajax回调方法)并不重要,有必要使用jquery选择器来分配自动增长功能。