【发布时间】:2011-11-29 20:02:08
【问题描述】:
如何让 textarea 最初只有 1 行,但是当文本到达行尾时添加另一行,并继续这样做直到最多 5 行?
【问题讨论】:
如何让 textarea 最初只有 1 行,但是当文本到达行尾时添加另一行,并继续这样做直到最多 5 行?
【问题讨论】:
类似这样的:
<textarea id="foo" rows="1" cols="40"></textarea>
$(function () {
$("#foo").on("keyup", function () {
if ($(this).attr('rows') < 5 &&
parseInt($(this).val().length/$(this).attr('cols')) >= $(this).attr('rows'))
$(this).attr("rows", parseInt($(this).attr("rows"))+1);
});
});
edit 处理换行的轻微改进:
$(function () {
$("#foo").on("keyup", function (e) {
if ($(this).attr('rows') < 5)
{
if (
parseInt($(this).val().length/$(this).attr('cols'))+
($(this).val().split("\n").length-1)
>=
$(this).attr('rows')
)
$(this).attr("rows", parseInt($(this).attr("rows"))+1);
if (e.keyCode == 13)
{
$(this).attr("rows", parseInt($(this).attr("rows"))+1);
}
}
});
});
【讨论】:
This A List Part article 对如何最好地实现此功能进行了深入的分步说明。
【讨论】:
我从 Jake Feasel 的回答中得到了这个想法,它不仅适用于扩展,而且还适用于收缩 textarea,以防内容较少。
HTML
<textarea id="foo" rows="1" cols="40"></textarea>
<div id="stat"></div>
它还根据单独的 div 中的内容显示所需的理想行数
CSS
#foo
{
resize:none;
}
这是必需的,因为一旦使用此处理程序调整了 textarea 的大小,代码就会停止工作
JS
$(function () {
$("#foo").on("keyup", function (e) {
var idealRows = parseInt($(this).val().length/$(this).attr('cols'))+
($(this).val().split("\n").length-1)+1 ;
var rows = $(this).attr('rows');
// for the bugging scroll bar
if(rows > 4) $('#foo').css('overflow','auto')
else $('#foo').css('overflow','hidden')
// for expanding and contracting
if( (idealRows > rows) && (rows < 5) || (idealRows < rows) && (rows > 1))
$(this).attr("rows", idealRows);
});
});
演示:http://jsfiddle.net/roopunk/xPdaP/3/
请注意,它还负责在 keyDown 和 keyUp 之间弹出的滚动条。 IMO:这有点麻烦。
注意 希望这可以帮助!:)
【讨论】:
查看 Elastic jQuery 插件:http://unwrongest.com/projects/elastic/
您可以将 CSS 上的 max-height 属性与 textarea 的 maxlength 结合使用,将其限制为 5 行。
【讨论】:
下载这个插件:http://james.padolsey.com/demos/plugins/jQuery/autoresize.jquery.js
$('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
});
【讨论】: