我需要<textarea>
垂直成長,如在用戶類型,我發現這個代碼在網上http://perplexed.co.uk/596_expanding_textarea_as_you_type.htm 我希望它被寫在jQuery
但是我把代碼放到jQuery
這是行不通的。Autoexpanding textarea的使用jQuery
這是JavaScript版本:
<textarea id="text"></textarea>
var textArea = document.getElementById('text')
textArea.addEventListener('input', function() {
while (
textArea.rows > 1 && textArea.scrollHeight < textArea.offsetHeight) {
textArea.rows--;
}
var h = 0;
while (textArea.scrollHeight > textArea.offsetHeight && h !== textArea.offsetHeight) {
h = textArea.offsetHeight;
textArea.rows++;
}
textArea.rows++
});
小提琴http://jsfiddle.net/dcdeiv/dsL6g/3/
但我不希望使用一個ID或一類,我想,要對每個textarea的工作,所以我tryed使用一個每個功能:
<textarea></textarea>
$.fn.growRows = function() {
return this.each(function() {
var textArea = $(this),
scrollHeight = textArea.scrollTop(),
offsetHeight = textArea.height(),
rows = textArea.attr(rows),
h = 0;
textArea.keyup(function() {
while (rows > 1 && scrollHeight < offsetHeight) {
rows--;
}
while (scrollHeight > offsetHeight && h !== offsetHeight) {
h = offsetHeight;
rows++;
}
rows++;
});
});
}
$('textarea').growRows();
,但它不工作無論如何。
小提琴http://jsfiddle.net/dcdeiv/BQB4M/
http://www.jacklmoore.com/autosize/ –