Javascript 输入文本时扩展的 CSS 文本区域
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4954252/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
CSS Textarea that expands as you type text
提问by Spencer
I have a Textarea where users can input text. By default it has a height of 17px. However if users insert a large amount of text, I want the text area to expand accordingly. Is there a way to do this with CSS ? Thanks in advance!!
我有一个 Textarea,用户可以在其中输入文本。默认情况下,它的高度为 17px。但是,如果用户插入大量文本,我希望文本区域相应地扩展。有没有办法用 CSS 做到这一点?提前致谢!!
采纳答案by Hussein
This cannot be done with CSS alone. try the autogrow jquery plugin. https://github.com/jaz303/jquery-grab-bag/blob/master/javascripts/jquery.autogrow-textarea.js
这不能单独使用 CSS 来完成。尝试自动增长 jquery 插件。 https://github.com/jaz303/jquery-grab-bag/blob/master/javascripts/jquery.autogrow-textarea.js
You can also see autogrow demo here http://onehackoranother.com/projects/jquery/jquery-grab-bag/autogrow-textarea.html
您还可以在此处查看自动增长演示http://onehackoranother.com/projects/jquery/jquery-grab-bag/autogrow-textarea.html
It's lightweight and easy to use. Here's how it's done. Define your textarea id. Include the jquery js file before </body>
. Then between script tags, issue the jquery command $("#txtInput").autoGrow();
它重量轻且易于使用。这是它的完成方式。定义你的 textarea id。在 .js 文件之前包含 jquery js 文件</body>
。然后在脚本标签之间,发出 jquery 命令$("#txtInput").autoGrow();
<body>
<textarea id="txtInput"></textarea>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"></script>
<script>
$("#txtInput").autogrow();
</script>
</body>
回答by sirkitree
This jQuery plugin is a really great one: http://www.Hymanlmoore.com/autosize
这个 jQuery 插件真的很棒:http: //www.Hymanlmoore.com/autosize
I've tested a bunch of these and this is by far the nicest. Also gives an example of using a CSS transition effect which is pretty slick.
我已经测试了很多这些,这是迄今为止最好的。还给出了一个使用 CSS 过渡效果的例子,它非常漂亮。
回答by Stephen Tremaine
**Note this is very similar to Woody's answer above but wanted to expand upon it a little and provide a running code example now that Stack allows us to embed them.
**请注意,这与上面 Woody 的回答非常相似,但想对其进行一些扩展并提供一个运行代码示例,因为 Stack 允许我们嵌入它们。
After reading through all of this and trying a couple of plugins, I found that none of this quite worked as I had hoped. I did the following - there is a slight jitter at the top of the field as you scroll before it expands, but it works for me. I used jquery, but can be done with javascript just as easily by grabbing the padding values instead of using inner height:
在阅读了所有这些并尝试了几个插件后,我发现这些都没有像我希望的那样奏效。我做了以下事情 - 在它展开之前滚动时,字段顶部有轻微的抖动,但它对我有用。我使用了 jquery,但可以通过抓取填充值而不是使用内部高度来使用 javascript 轻松完成:
- Set a minimum height on the textareain CSS
- Set overflow to hidden for vertical scrolling (I just wanted to expand vertically)
- Set the height to the scroll height less padding on each keyupevent if scroll height was higher than height + padding (innerHeight).
- If scroll height was not taller, I re-set the height to 1, and then set the height to the scroll height less padding (to shrink the height). If you don't reset to a smaller height initially the scroll height won't shrink.
- 在 CSS 中的textarea上设置最小高度
- 将溢出设置为隐藏以进行垂直滚动(我只是想垂直扩展)
- 如果滚动高度高于高度 + 填充(innerHeight),则在每个keyup事件上将高度设置为滚动高度减去填充。
- 如果滚动高度不高,我将高度重新设置为 1,然后将高度设置为滚动高度减去填充(缩小高度)。如果最初不重置为较小的高度,则滚动高度不会缩小。
$(function() {
$('#myTextArea').on('keyup paste', function() {
var $el = $(this),
offset = $el.innerHeight() - $el.height();
if ($el.innerHeight() < this.scrollHeight) {
// Grow the field if scroll height is smaller
$el.height(this.scrollHeight - offset);
} else {
// Shrink the field and then re-set it to the scroll height in case it needs to shrink
$el.height(1);
$el.height(this.scrollHeight - offset);
}
});
});
#myTextArea {
width: 250px;
min-height: 35px;
overflow-y: hidden;
}
<script src="https://code.jquery.com/jquery-2.2.3.min.js"></script>
<textarea id="myTextArea" placeholder="Hit enter a few times, it should expand"></textarea>
回答by momciloo
I know this is a little bit late, but I have to say there is a way to use <div>
with contenteditable
attribute to simulate desired behaviour.
我知道这有点晚了,但我不得不说有一种方法可以使用<div>
withcontenteditable
属性来模拟所需的行为。
.textareaElement {
width: 300px;
min-height: 17px;
border: 1px solid #ccc;
max-height: 150px;
overflow-x: hidden;
overflow-y: auto;
}
<div class="textareaElement" contenteditable></div>
Just set your min and max height, with proper overflow values, and you have fully functional pure CSS expanding textbox, that is also well supported.
只需设置您的最小和最大高度,使用适当的溢出值,您就拥有功能齐全的纯 CSS 扩展文本框,这也得到了很好的支持。
回答by Woody Payne
You don't need a plugin for this. This works on textareas of any size, height or row size and will only work when the contents exceeds the textarea. Firstly set the overflow on your target textareas to hidden and resize to none, then add the following functionality to the textareas you want to autogrow. Not only will it increase the textarea's size as the user types, it'll also auto-shrink it when they delete stuff.
您不需要为此使用插件。这适用于任何大小、高度或行大小的 textarea,并且仅在内容超出 textarea 时才有效。首先将目标文本区域上的溢出设置为隐藏并将大小调整为无,然后将以下功能添加到要自动增长的文本区域。它不仅会在用户键入时增加 textarea 的大小,还会在删除内容时自动缩小它。
$('textarea').on('paste input', function () {
if ($(this).outerHeight() > this.scrollHeight){
$(this).height(1)
}
while ($(this).outerHeight() < this.scrollHeight + parseFloat($(this).css("borderTopWidth")) + parseFloat($(this).css("borderBottomWidth"))){
$(this).height($(this).height() + 1)
}
});
It works by measuring if the scroll height of the textarea is bigger than the outer height, which it only will be if there's more text than the textarea can hold - and it takes border size into account for higher accuracy. Using paste and input means it will only increase when the user physically changes the value of the textarea, as opposed to when they press any key. It's petty but a textarea shouldn't grow when somebody presses an arrow key or something.
它通过测量 textarea 的滚动高度是否大于外部高度来工作,只有当文本多于 textarea 可以容纳的文本时才会出现这种情况 - 并且它考虑了边框大小以获得更高的准确性。使用粘贴和输入意味着它只会在用户物理更改 textarea 的值时增加,而不是在他们按下任意键时。它很小,但是当有人按下箭头键或其他东西时,textarea 不应该增长。
It might be prudent to add a No JS option that re-enables overflow and resizing for those who don't have Javascript, else they'll be stuck with a tiny box.
为那些没有 Javascript 的人添加一个 No JS 选项来重新启用溢出和调整大小可能是谨慎的,否则他们会被一个小盒子卡住。
回答by Nikita Barsukov
Use JavaScript for this.
为此使用 JavaScript。
This script checks the lenth of text area after every keystroke there (copypasta from here):
此脚本在每次击键后检查文本区域的长度(从此处复制粘贴):
<textarea name="x" onKeyUp="SetNewSize(this);" cols="5" rows="4"></textarea>
<script language="javascript">
function SetNewSize(textarea){
if (textarea.value.length > 5){
textarea.cols = 50;
textarea.rows = 50;
} else{
textarea.cols = 10;
textarea.rows = 15;
}
}
</script>
回答by N0XT
A little bit late, but this worked for me like a charm, it's in jquery:
有点晚了,但这对我来说就像一种魅力,它在 jquery 中:
This textarea have a limit height of 200px, and a starting height of 22px. The padding helps a lot to keep the text in a good place, but, we have to play with weights depending on the size of the font.
此文本区域的限制高度为 200 像素,起始高度为 22 像素。填充有助于将文本保持在一个好的位置,但是,我们必须根据字体的大小来调整权重。
There is a similar answer in another question, but this one is a little bit more complete.
在另一个问题中有一个类似的答案,但这个更完整一点。
$('textarea').each(function () {
// Do something if you want
}).on('input', function () {
this.style.height = 'auto';
// Customize if you want
this.style.height = (this.scrollHeight - 30) + 'px'; //The weight is 30
});
textarea{
padding: 7px;
width: 50%;
height: 22px;
max-height: 200px;
resize: none;
overflow-y: scroll;
font-size: 16px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>Textarea:</div>
<textarea></textarea>
回答by Glenn Kreisel
This seems to be much more efficient and handles max-height
这似乎更有效率并且可以处理最大高度
$(ctrl).on('paste input', function () {
var dyLineHeight, dyMax, dyHeight;
if ($(this).outerHeight() > this.scrollHeight)
$(this).height($(this).outerHeight() - parseFloat($(this).css("borderBottomWidth")) - parseFloat($(this).css("borderTopWidth")));
dyLineHeight = Math.max(3, parseInt($(this).css("line-height")));
dyMax = parseInt($(this).css("max-height"));
while ($(this).outerHeight() < this.scrollHeight + parseFloat($(this).css("borderTopWidth")) + parseFloat($(this).css("borderBottomWidth")))
{
dyHeight = $(this).height();
if (dyHeight >= dyMax)
break;
$(this).height(dyHeight + dyLineHeight)
}
});
回答by Prem Kumar Maurya
Expanding textarea as you type
键入时扩展文本区域
Type something in textarea to see the effect
在 textarea 中输入一些内容以查看效果
<script>
function increseRows(selector)
{
$(selector).attr("rows", $(selector).val().split("\n").length+1||2);
}
</script>
回答by DigitalDan
I use the following (with jQuery of course):
我使用以下(当然使用 jQuery):
$(function () {
'use strict';
$("textarea").on('change keyup paste input', function () {
$(this).attr("rows", Math.max($(this).val().split("\n").length || 1, $(this).attr("rows") || 1));
$(this).css("width", $(this).css("width"));
}).trigger('change');
});
Note that it responds to various events, only increases the number of lines (i.e. doesn't decrease), triggers an initial change (e.g. to resize when browsing back to a form with lots of lines)
请注意,它响应各种事件,仅增加行数(即不会减少),触发初始更改(例如,在浏览回具有大量行的表单时调整大小)