【发布时间】:2010-06-01 08:26:04
【问题描述】:
如何使用 jQuery 使文本区域自动扩展?
我有一个用于解释会议议程的文本框,所以当我的议程文本不断扩大该文本框区域时,我想扩展该文本框。
【问题讨论】:
-
我认为 textarea 是可自动扩展的。
-
请考虑更改您的问题并删除“jQuery”一词
标签: jquery
如何使用 jQuery 使文本区域自动扩展?
我有一个用于解释会议议程的文本框,所以当我的议程文本不断扩大该文本框区域时,我想扩展该文本框。
【问题讨论】:
标签: jquery
如果你不想要插件,有一个非常简单的解决方案
$("textarea").keyup(function(e) {
while($(this).outerHeight() < this.scrollHeight + parseFloat($(this).css("borderTopWidth")) + parseFloat($(this).css("borderBottomWidth"))) {
$(this).height($(this).height()+1);
};
});
在jsFiddle I used to answer another textarea question here 中查看它。
要回答反向执行或在删除文本时使其变小的问题:jsFiddle
如果你确实想要一个插件
【讨论】:
if (this.clientHeight < this.scrollHeight) { this.style.height = this.scrollHeight + 'px'; }
我试过很多次
this one is great. 链接已失效。较新的版本是available here。请参阅下面的旧版本。
您可以尝试在 textarea 中按住 enter 键。与其他自动扩展 textarea 插件对比效果......
编辑根据评论
$(function() {
$('#txtMeetingAgenda').autogrow();
});
注意:您应该包含所需的 js 文件...
为了防止文本区域中的滚动条在扩展/收缩过程中闪烁,您也可以将overflow设置为hidden:
$('#textMeetingAgenda').css('overflow', 'hidden').autogrow()
更新:
上面的链接坏了。但是你仍然可以得到javascript文件here。
【讨论】:
增长/缩小文本区域。此演示使用 jQuery 进行事件绑定,但无论如何都不是必须的。
(不支持 IE - IE 不响应 rows 属性更改)
<textarea class='autoExpand' rows='3' data-min-rows='3' placeholder='Auto-Expanding Textarea'></textarea>
textarea{
display:block;
box-sizing: padding-box;
overflow:hidden;
padding:10px;
width:250px;
font-size:14px;
margin:50px auto;
border-radius:8px;
border:6px solid #556677;
}
$(document)
.one('focus.textarea', '.autoExpand', function(){
var savedValue = this.value;
this.value = '';
this.baseScrollHeight = this.scrollHeight;
this.value = savedValue;
})
.on('input.textarea', '.autoExpand', function(){
var minRows = this.getAttribute('data-min-rows')|0,
rows;
this.rows = minRows;
rows = Math.ceil((this.scrollHeight - this.baseScrollHeight) / 16);
this.rows = minRows + rows;
});
【讨论】:
你可以试试这个
$('#content').on('change keyup keydown paste cut', 'textarea', function () {
$(this).height(0).height(this.scrollHeight);
}).find('textarea').change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="content">
<textarea>How about it</textarea><br />
<textarea rows="5">111111
222222
333333
444444
555555
666666</textarea>
</div>
【讨论】:
【讨论】:
感谢 SpYk3HH,我从他的解决方案开始,并将其变成了这个解决方案,它增加了收缩功能,并且更简单更快,我想。
$("textarea").keyup(function(e) {
$(this).height(30);
$(this).height(this.scrollHeight + parseFloat($(this).css("borderTopWidth")) + parseFloat($(this).css("borderBottomWidth")));
});
在当前的 Chrome、Firefox 和 Android 2.3.3 浏览器中测试。
您可能会在某些浏览器中看到滚动条闪烁。添加这个 CSS 来解决这个问题。
textarea{ overflow:hidden; }
【讨论】:
1px似乎更好)
要定义一个自动扩展的文本区域,你必须做两件事:
这是一个手工制作的函数来完成任务。
适用于几乎所有浏览器 (。方法如下:
//Here is an event to get TextArea expand when you press Enter Key in it.
// intiate a keypress event
$('textarea').keypress(function (e) {
if(e.which == 13) {
var control = e.target;
var controlHeight = $(control).height();
//add some height to existing height of control, I chose 17 as my line-height was 17 for the control
$(control).height(controlHeight+17);
}
});
$('textarea').blur(function (e) {
var textLines = $(this).val().trim().split(/\r*\n/).length;
$(this).val($(this).val().trim()).height(textLines*17);
});
HERE 是关于此的帖子。
【讨论】:
我之前用过Textarea Expander jQuery 插件,效果不错。
【讨论】:
每个人都应该试试这个 jQuery 插件:xautoresize-jquery。真的很好,应该可以解决你的问题。
【讨论】:
function autosize(textarea) {
$(textarea).height(1); // temporarily shrink textarea so that scrollHeight returns content height when content does not fill textarea
$(textarea).height($(textarea).prop("scrollHeight"));
}
$(document).ready(function () {
$(document).on("input", "textarea", function() {
autosize(this);
});
$("textarea").each(function () {
autosize(this);
});
});
(这在 Internet Explorer 9 或更早版本中不起作用,因为它使用了input 事件)
【讨论】:
我刚刚构建了这个函数来扩展页面加载时的文本区域。只需将each 改为keyup 即可在输入textarea 时出现。
// On page-load, auto-expand textareas to be tall enough to contain initial content
$('textarea').each(function(){
var pad = parseInt($(this).css('padding-top'));
if ($.browser.mozilla)
$(this).height(1);
var contentHeight = this.scrollHeight;
if (!$.browser.mozilla)
contentHeight -= pad * 2;
if (contentHeight > $(this).height())
$(this).height(contentHeight);
});
在 Chrome、IE9 和 Firefox 中测试。不幸的是,Firefox 有this bug,它为scrollHeight 返回了不正确的值,所以上面的代码包含一个(hacky)解决方法。
【讨论】:
我修复了 Reigel 提供的答案(已接受的答案)中的一些错误:
还有一些关于空间的问题。我没有看到双空格的解决方案,它们在阴影中显示为单个空格(html 渲染)。这不能通过使用 来解决,因为空格应该被打破。此外,文本区域在空格后换行,如果该空格没有空间,它将在较早的位置换行。欢迎提出建议。
更正的代码:
(function ($) {
$.fn.autogrow = function (options) {
var $this, minHeight, lineHeight, shadow, update;
this.filter('textarea').each(function () {
$this = $(this);
minHeight = $this.height();
lineHeight = $this.css('lineHeight');
$this.css('overflow','hidden');
shadow = $('<div></div>').css({
position: 'absolute',
'word-wrap': 'break-word',
top: -10000,
left: -10000,
width: $this.width(),
fontSize: $this.css('fontSize'),
fontFamily: $this.css('fontFamily'),
lineHeight: $this.css('lineHeight'),
resize: 'none'
}).appendTo(document.body);
update = function () {
shadow.css('width', $(this).width());
var val = this.value.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/\n/g, '<br/>')
.replace(/\s/g,' ');
if (val.indexOf('<br/>', val.length - 5) !== -1) { val += '#'; }
shadow.html(val);
$(this).css('height', Math.max(shadow.height(), minHeight));
};
$this.change(update).keyup(update).keydown(update);
update.apply(this);
});
return this;
};
}(jQuery));
【讨论】:
SpYk3HH 代码加上缩小尺寸。
function get_height(elt) {
return elt.scrollHeight + parseFloat($(elt).css("borderTopWidth")) + parseFloat($(elt).css("borderBottomWidth"));
}
$("textarea").keyup(function(e) {
var found = 0;
while (!found) {
$(this).height($(this).height() - 10);
while($(this).outerHeight() < get_height(this)) {
$(this).height($(this).height() + 1);
found = 1;
};
}
});
【讨论】:
这对我更有效:
$('.resiText').on('keyup input', function() {
$(this).css('height', 'auto').css('height', this.scrollHeight + (this.offsetHeight - this.clientHeight));
});
.resiText {
box-sizing: border-box;
resize: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea class="resiText"></textarea>
【讨论】:
人们似乎有过度工作的解决方案......
我就是这样做的:
$('textarea').keyup(function()
{
var
$this = $(this),
height = parseInt($this.css('line-height'), 10),
padTop = parseInt($this.css('padding-top'), 10),
padBot = parseInt($this.css('padding-bottom'), 10);
$this.height(0);
var
scroll = $this.prop('scrollHeight'),
lines = (scroll - padTop - padBot) / height;
$this.height(height * lines);
});
这将适用于长行,以及换行符.. 增长和缩小..
【讨论】:
我编写了这个似乎可以工作的 jquery 函数。
你需要在 css 中指定 min-height,除非你想做一些编码,否则它需要是两位数。即12px;
$.fn.expand_ta = function() {
var val = $(this).val();
val = val.replace(/</g, "<");
val = val.replace(/>/g, ">");
val += "___";
var ta_class = $(this).attr("class");
var ta_width = $(this).width();
var min_height = $(this).css("min-height").substr(0, 2);
min_height = parseInt(min_height);
$("#pixel_height").remove();
$("body").append('<pre class="'+ta_class+'" id="pixel_height" style="position: absolute; white-space: pre-wrap; visibility: hidden; word-wrap: break-word; width: '+ta_width+'px; height: auto;"></pre>');
$("#pixel_height").html(val);
var height = $("#pixel_height").height();
if (val.substr(-6) == "<br />"){
height = height + min_height;
};
if (height >= min_height) $(this).css("height", height+"px");
else $(this).css("height", min_height+"px");
}
【讨论】:
对于使用 Reigel 发布的插件的任何人,请注意这将禁用 Internet Explorer 中的撤消功能(去演示一下)。
如果这对您来说是个问题,那么我建议您改用 plugin posted by @richsage,因为它不会遇到这个问题。有关详细信息,请参阅 Searching for the Ultimate Resizing Textarea 上的第二个要点。
【讨论】:
还有一个非常酷的 bgrins/ExpandingTextareas (github) 项目,基于 Neill Jenkins 的出版物 Expanding Text Areas Made Elegant
【讨论】:
我想要动画和自动收缩。这种组合显然很难,因为人们为此想出了非常强烈的解决方案。我也做了多文本区域证明。而且它没有jQuery插件那么重。
我以 vsync 的回答(以及他为此做出的改进)为基础,http://codepen.io/anon/pen/vlIwj 是我改进的代码。
HTML
<textarea class='autoExpand' rows='3' data-min-rows='3' placeholder='Auto-Expanding Textarea'></textarea>
CSS
body{ background:#728EB2; }
textarea{
display:block;
box-sizing: padding-box;
overflow:hidden;
padding:10px;
width:250px;
font-size:14px;
margin:50px auto;
border-radius:8px;
border:6px solid #556677;
transition:all 1s;
-webkit-transition:all 1s;
}
JS
var rowheight = 0;
$(document).on('input.textarea', '.autoExpand', function(){
var minRows = this.getAttribute('data-min-rows')|0,
rows = this.value.split("\n").length;
$this = $(this);
var rowz = rows < minRows ? minRows : rows;
var rowheight = $this.attr('data-rowheight');
if(!rowheight){
this.rows = rowz;
$this.attr('data-rowheight', (this.clientHeight - parseInt($this.css('padding-top')) - parseInt($this.css('padding-bottom')))/ rowz);
}else{
rowz++;
this.style.cssText = 'height:' + rowz * rowheight + 'px';
}
});
【讨论】:
对此有很多答案,但我发现一些非常简单的事情,将 keyup 事件附加到 textarea 并检查 enter key press key code is 13
keyPressHandler(e){
if(e.keyCode == 13){
e.target.rows = e.target.rows + 1;
}
}
这将为您的文本区域添加另一行,您可以使用 CSS 设置宽度样式。
【讨论】:
假设您正在尝试使用 Knockout 来完成此操作……方法如下:
在页面中:
<textarea data-bind="event: { keyup: $root.GrowTextArea }"></textarea>
在视图模型中:
self.GrowTextArea = function (data, event) {
$('#' + event.target.id).height(0).height(event.target.scrollHeight);
}
即使您像我一样有多个由 Knockout foreach 创建的文本区域,这也应该有效。
【讨论】:
简单的解决方案:
HTML:
<textarea class='expand'></textarea>
JS:
$('textarea.expand').on('input', function() {
$(this).scrollTop($(this).height());
});
$('textarea.expand').scroll(function() {
var h = $(this).scrollTop();
if (h > 0)
$(this).height($(this).height() + h);
});
【讨论】:
最简单的解决方案:
html:
<textarea class="auto-expand"></textarea>
css:
.auto-expand {
overflow:hidden;
min-height: 80px;
}
js (jquery):
$(document).ready(function () {
$("textarea.auto-expand").focus(function () {
var $minHeight = $(this).css('min-height');
$(this).on('input', function (e) {
$(this).css('height', $minHeight);
var $newHeight = $(this)[0].scrollHeight;
$(this).css('height', $newHeight);
});
});
});
【讨论】:
纯JS的解决方案
function autoSize() {
if (element) {
element.setAttribute('rows', 2) // minimum rows
const rowsRequired = parseInt(
(element.scrollHeight - TEXTAREA_CONFIG.PADDING) / TEXTAREA_CONFIG.LINE_HEIGHT
)
if (rowsRequired !== parseInt(element.getAttribute('rows'))) {
element.setAttribute('rows', rowsRequired)
}
}
}
【讨论】:
这是我最终使用的解决方案。我想要一个内联解决方案,到目前为止这似乎工作得很好:
<textarea onkeyup="$(this).css('height', 'auto').css('height', this.scrollHeight + this.offsetHeight - this.clientHeight);"></textarea>
【讨论】:
function autoResizeTextarea() {
for (let index = 0; index < $('textarea').length; index++) {
let element = $('textarea')[index];
let offset = element.offsetHeight - element.clientHeight;
$(element).css('resize', 'none');
$(element).on('input', function() {
$(this).height(0).height(this.scrollHeight - offset - parseInt($(this).css('padding-top')));
});
}
}
https://codepen.io/nanachi1/pen/rNNKrzQ
这应该可以。
【讨论】:
这对我来说效果很好
$(".textarea").on("keyup input", function(){
$(this).css('height', 'auto').css('height', this.scrollHeight+
(this.offsetHeight - this.clientHeight));
});
【讨论】:
@Georgiy Ivankin 在评论中提出了建议, 我成功地使用了它:) -- ,但有细微的变化:
$('#note').on('keyup',function(e){
var maxHeight = 200;
var f = document.getElementById('note');
if (f.clientHeight < f.scrollHeight && f.scrollHeight < maxHeight )
{ f.style.height = f.scrollHeight + 'px'; }
});
达到最大高度 200px 后停止扩展
【讨论】:
老问题,但你可以这样做:
html:
<textarea class="text-area" rows="1"></textarea>
jquery:
var baseH; // base scroll height
$('body')
.one('focus.textarea', '.text-area', function(e) {
baseH = this.scrollHeight;
})
.on('input.textarea', '.text-area', function(e) {
if(baseH < this.scrollHeight) {
$(this).height(0).height(this.scrollHeight);
}
else {
$(this).height(0).height(baseH);
}
});
这样,自动调整大小将应用于任何具有“文本区域”类的文本区域。删除文本时也会缩小。
jsfiddle:
【讨论】:
试试这个:
$('textarea[name="mytextarea"]').on('input', function(){
$(this).height('auto').height($(this).prop('scrollHeight') + 'px');
}).trigger('input');
【讨论】: