如何自动调整大小a textarea使用原型?
-
08-06-2019 - |
题
我目前正在内部销售的应用为我工作的公司,并且我已经有了一个形式,允许用户改变交货地址。
现在我觉得它看起来更漂亮,如果textarea我使用的主要地址的详细信息将仅仅是采取该区域的文本,并自动调整,如果该案文被更改。
这里有一个截它。
任何想法?
@克里斯
一个好的点,但是有原因我想要的调整。我希望该地区需要的领域中所载的信息。正如你可以看拍摄的画面,如果我有一个固定的文本区域,它需要一个公平的怪人的垂直空间。
我可以减少的字体,但我需要地址是大型和可读性。现在我可以减少尺寸的文本区域,但后来我有问题的人有一个地址线,需要3或4(一个需要5)条线。需要有用户使用一个滚动是一个主要没有-没有。
我想我应该多一点的具体。我后垂直的调整,并且宽度无论多。唯一的问题发生这种情况,是ISO数(大"1")被推下地址时,窗口的宽度太小(如你可以看到的截图)。
这不是具有gimick;这是关于具有文领域的用户可编辑不会采取不必要的空间,但是将显示所有文本。
虽然如果有人来了另一种方式来处理这个问题我开到这一点。
我已经修改的代码一点,因为它是有点奇怪。我改变了它来激活上的候,把,因为它不会考虑的角色,只是输入的。
resizeIt = function() {
var str = $('iso_address').value;
var cols = $('iso_address').cols;
var linecount = 0;
$A(str.split("\n")).each(function(l) {
linecount += 1 + Math.floor(l.length / cols); // Take into account long lines
})
$('iso_address').rows = linecount;
};
解决方案
Facebook不,当你写信,对人民的墙,但只有重新调整垂直。
水平调整的罢工我是一个烂摊子,由于字包裹,长线,等等,但是垂直的调整似乎是非常安全的,漂亮。
没有Facebook使用新手我知道有没有提到任何关于它的或被混淆。我会用这个作为证据说'继续前进,实现它'。
一些代码做到这一点,使用 原型 (因为这是我熟悉):
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="http://www.google.com/jsapi"></script>
<script language="javascript">
google.load('prototype', '1.6.0.2');
</script>
</head>
<body>
<textarea id="text-area" rows="1" cols="50"></textarea>
<script type="text/javascript" language="javascript">
resizeIt = function() {
var str = $('text-area').value;
var cols = $('text-area').cols;
var linecount = 0;
$A(str.split("\n")).each( function(l) {
linecount += Math.ceil( l.length / cols ); // Take into account long lines
})
$('text-area').rows = linecount + 1;
};
// You could attach to keyUp, etc. if keydown doesn't work
Event.observe('text-area', 'keydown', resizeIt );
resizeIt(); //Initial on load
</script>
</body>
</html>
PS:显然,这JavaScript code是很天真的和不好的测试,你可能不想利用它在本框有的小说,但你会得到一般想法。
其他提示
一个细化其中一些答案是让CSS做更多的工作。
基本路线似乎是:
- 创建一个容器元件举行
textarea
和一个隐藏的div
- 使用Javascript,保持
textarea
's的内容同步的div
's - 让浏览器做的工作计算的高度,div
- 因为将浏览器处理渲染/大小的隐藏
div
, 我们避免 明确设定textarea
's的高度。
document.addEventListener('DOMContentLoaded', () => {
textArea.addEventListener('change', autosize, false)
textArea.addEventListener('keydown', autosize, false)
textArea.addEventListener('keyup', autosize, false)
autosize()
}, false)
function autosize() {
// Copy textarea contents to div browser will calculate correct height
// of copy, which will make overall container taller, which will make
// textarea taller.
textCopy.innerHTML = textArea.value.replace(/\n/g, '<br/>')
}
html, body, textarea {
font-family: sans-serif;
font-size: 14px;
}
.textarea-container {
position: relative;
}
.textarea-container > div, .textarea-container > textarea {
word-wrap: break-word; /* make sure the div and the textarea wrap words in the same way */
box-sizing: border-box;
padding: 2px;
width: 100%;
}
.textarea-container > textarea {
overflow: hidden;
position: absolute;
height: 100%;
}
.textarea-container > div {
padding-bottom: 1.5em; /* A bit more than one additional line of text. */
visibility: hidden;
width: 100%;
}
<div class="textarea-container">
<textarea id="textArea"></textarea>
<div id="textCopy"></div>
</div>
这里是另一个技术调整textarea.
- 使用的像素的高度而不是线路高度:更准确地处理行包装,如果一个成比例的字体使用。
- 接受身份证或元件作为输入
- 接受一个可选的最大高度的参数-有用的,如果你不想让我们的文本区域的增长超过某个特定大小(保持它的所有屏幕上,避免破布局,等等。)
- 测试的火狐3和 Internet Explorer6
代码: (plain vanilla JavaScript)
function FitToContent(id, maxHeight)
{
var text = id && id.style ? id : document.getElementById(id);
if (!text)
return;
/* Accounts for rows being deleted, pixel value may need adjusting */
if (text.clientHeight == text.scrollHeight) {
text.style.height = "30px";
}
var adjustedHeight = text.clientHeight;
if (!maxHeight || maxHeight > adjustedHeight)
{
adjustedHeight = Math.max(text.scrollHeight, adjustedHeight);
if (maxHeight)
adjustedHeight = Math.min(maxHeight, adjustedHeight);
if (adjustedHeight > text.clientHeight)
text.style.height = adjustedHeight + "px";
}
}
演示: (使用jQuery,目标在textarea我输入吧-如果你有 萤火虫 安装、粘贴这两种样品进入控制台并试验在这一页)
$("#post-text").keyup(function()
{
FitToContent(this, document.documentElement.clientHeight)
});
可能最短的解决方案:
jQuery(document).ready(function(){
jQuery("#textArea").on("keydown keyup", function(){
this.style.height = "1px";
this.style.height = (this.scrollHeight) + "px";
});
});
这种方式不需要任何隐藏的div或类似的东西。
注:你可能有一起玩 this.style.height = (this.scrollHeight) + "px";
根据你的风格textarea(行高,填补这种东西).
这里有一个 原型 版本的调整文本地区,不依赖于数列在textarea.这是一个卓越的技术,因为它可以让你控制的文本区域通过CSS以及已经变宽度textarea.此外,这一版本显示的数字。虽然不要求,这是一个非常有用的特征和易删除不必要的。
//inspired by: http://github.com/jaz303/jquery-grab-bag/blob/63d7e445b09698272b2923cb081878fd145b5e3d/javascripts/jquery.autogrow-textarea.js
if (window.Widget == undefined) window.Widget = {};
Widget.Textarea = Class.create({
initialize: function(textarea, options)
{
this.textarea = $(textarea);
this.options = $H({
'min_height' : 30,
'max_length' : 400
}).update(options);
this.textarea.observe('keyup', this.refresh.bind(this));
this._shadow = new Element('div').setStyle({
lineHeight : this.textarea.getStyle('lineHeight'),
fontSize : this.textarea.getStyle('fontSize'),
fontFamily : this.textarea.getStyle('fontFamily'),
position : 'absolute',
top: '-10000px',
left: '-10000px',
width: this.textarea.getWidth() + 'px'
});
this.textarea.insert({ after: this._shadow });
this._remainingCharacters = new Element('p').addClassName('remainingCharacters');
this.textarea.insert({after: this._remainingCharacters});
this.refresh();
},
refresh: function()
{
this._shadow.update($F(this.textarea).replace(/\n/g, '<br/>'));
this.textarea.setStyle({
height: Math.max(parseInt(this._shadow.getHeight()) + parseInt(this.textarea.getStyle('lineHeight').replace('px', '')), this.options.get('min_height')) + 'px'
});
var remaining = this.options.get('max_length') - $F(this.textarea).length;
this._remainingCharacters.update(Math.abs(remaining) + ' characters ' + (remaining > 0 ? 'remaining' : 'over the limit'));
}
});
创造的部件通过调用 new Widget.Textarea('element_id')
.默认选择可以替代它们传递作为一个目的,例如 new Widget.Textarea('element_id', { max_length: 600, min_height: 50})
.如果你想要创造的所有文字区域的网页,做些什么,如:
Event.observe(window, 'load', function() {
$$('textarea').each(function(textarea) {
new Widget.Textarea(textarea);
});
});
这里是一个解决方案 JQuery
:
$(document).ready(function() {
var $abc = $("#abc");
$abc.css("height", $abc.attr("scrollHeight"));
})
abc
是一个 teaxtarea
.
检查下面的链接:http://james.padolsey.com/javascript/jquery-plugin-autoresize/
$(document).ready(function () {
$('.ExpandableTextCSS').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:20,
//Textarea height limit
limit:10
});
});
只是重新审视这一点,我做了一点点整洁的(虽然有人是充分的瓶子上 原型/JavaScript可以提出改进建议?).
var TextAreaResize = Class.create();
TextAreaResize.prototype = {
initialize: function(element, options) {
element = $(element);
this.element = element;
this.options = Object.extend(
{},
options || {});
Event.observe(this.element, 'keyup',
this.onKeyUp.bindAsEventListener(this));
this.onKeyUp();
},
onKeyUp: function() {
// We need this variable because "this" changes in the scope of the
// function below.
var cols = this.element.cols;
var linecount = 0;
$A(this.element.value.split("\n")).each(function(l) {
// We take long lines into account via the cols divide.
linecount += 1 + Math.floor(l.length / cols);
})
this.element.rows = linecount;
}
}
只是它呼吁:
new TextAreaResize('textarea_id_name_here');
我做了一些相当容易的。第一,我把TextArea成DIV。第二,我呼吁 ready
功能要这个脚本。
<div id="divTable">
<textarea ID="txt" Rows="1" TextMode="MultiLine" />
</div>
$(document).ready(function () {
var heightTextArea = $('#txt').height();
var divTable = document.getElementById('divTable');
$('#txt').attr('rows', parseInt(parseInt(divTable .style.height) / parseInt(altoFila)));
});
简单的。它是最大高度的div一旦它被渲染,分通过高度一个TextArea的一行。
我需要这个功能对于我自己,但没有人从这里曾作为我需要他们。
所以我用猎户座的代码并改变它。
我加入一个最低的高度,以便在毁它不会太小。
function resizeIt( id, maxHeight, minHeight ) {
var text = id && id.style ? id : document.getElementById(id);
var str = text.value;
var cols = text.cols;
var linecount = 0;
var arStr = str.split( "\n" );
$(arStr).each(function(s) {
linecount = linecount + 1 + Math.floor(arStr[s].length / cols); // take into account long lines
});
linecount++;
linecount = Math.max(minHeight, linecount);
linecount = Math.min(maxHeight, linecount);
text.rows = linecount;
};
像是答案的@memical.
但是我发现了一些改进。你可以使用延 height()
功能。但要知道的填充和填补底的像素。否则你textarea将增长过快。
$(document).ready(function() {
$textarea = $("#my-textarea");
// There is some diff between scrollheight and height:
// padding-top and padding-bottom
var diff = $textarea.prop("scrollHeight") - $textarea.height();
$textarea.live("keyup", function() {
var height = $textarea.prop("scrollHeight") - diff;
$textarea.height(height);
});
});
我的解决方案不使用jQuery(因为有时他们不必是相同的东西)下。虽然这只是测试 Internet Explorer7, ,所以该社区可以指出所有原因,这是错误的:
textarea.onkeyup = function () { this.style.height = this.scrollHeight + 'px'; }
迄今为止我真的喜欢它如何工作,而我不关心其他浏览器,所以我可能会应用于所有我的文字区域:
// Make all textareas auto-resize vertically
var textareas = document.getElementsByTagName('textarea');
for (i = 0; i<textareas.length; i++)
{
// Retain textarea's starting height as its minimum height
textareas[i].minHeight = textareas[i].offsetHeight;
textareas[i].onkeyup = function () {
this.style.height = Math.max(this.scrollHeight, this.minHeight) + 'px';
}
textareas[i].onkeyup(); // Trigger once to set initial height
}
这是一个扩展的原型部件,杰里米*张贴在六月4日:
它会停止的用户进入更多的人物如果你使用限制在文本域。它检查,如果有字的左边。如果用户副本的文字进textarea,文字被切断在最大。长度:
/**
* Prototype Widget: Textarea
* Automatically resizes a textarea and displays the number of remaining chars
*
* From: http://stackoverflow.com/questions/7477/autosizing-textarea
* Inspired by: http://github.com/jaz303/jquery-grab-bag/blob/63d7e445b09698272b2923cb081878fd145b5e3d/javascripts/jquery.autogrow-textarea.js
*/
if (window.Widget == undefined) window.Widget = {};
Widget.Textarea = Class.create({
initialize: function(textarea, options){
this.textarea = $(textarea);
this.options = $H({
'min_height' : 30,
'max_length' : 400
}).update(options);
this.textarea.observe('keyup', this.refresh.bind(this));
this._shadow = new Element('div').setStyle({
lineHeight : this.textarea.getStyle('lineHeight'),
fontSize : this.textarea.getStyle('fontSize'),
fontFamily : this.textarea.getStyle('fontFamily'),
position : 'absolute',
top: '-10000px',
left: '-10000px',
width: this.textarea.getWidth() + 'px'
});
this.textarea.insert({ after: this._shadow });
this._remainingCharacters = new Element('p').addClassName('remainingCharacters');
this.textarea.insert({after: this._remainingCharacters});
this.refresh();
},
refresh: function(){
this._shadow.update($F(this.textarea).replace(/\n/g, '<br/>'));
this.textarea.setStyle({
height: Math.max(parseInt(this._shadow.getHeight()) + parseInt(this.textarea.getStyle('lineHeight').replace('px', '')), this.options.get('min_height')) + 'px'
});
// Keep the text/character count inside the limits:
if($F(this.textarea).length > this.options.get('max_length')){
text = $F(this.textarea).substring(0, this.options.get('max_length'));
this.textarea.value = text;
return false;
}
var remaining = this.options.get('max_length') - $F(this.textarea).length;
this._remainingCharacters.update(Math.abs(remaining) + ' characters remaining'));
}
});
@memical 有一个很棒的解决方案设置的高度textarea上的页面加载有文化,但对我的应用程序,我希望能够增加高度的文本区域作用者加入更多内容。我建立了关memical的解决方案如下:
$(document).ready(function() {
var $textarea = $("p.body textarea");
$textarea.css("height", ($textarea.attr("scrollHeight") + 20));
$textarea.keyup(function(){
var current_height = $textarea.css("height").replace("px", "")*1;
if (current_height + 5 <= $textarea.attr("scrollHeight")) {
$textarea.css("height", ($textarea.attr("scrollHeight") + 20));
}
});
});
这不是很顺利,但它也不是一个面向客户的应用程序,因此光滑并不真正的问题。(有了这是面向客户,我可能会只是使用自动调整jQuery插件。)
对于那些编码即和遇到这个问题。即有一个小伎俩,使得100%CSS。
<TEXTAREA style="overflow: visible;" cols="100" ....></TEXTAREA>
你甚至可以提供有价值的行="n",它即将会忽略的,但其他浏览器将使用。我真的很讨厌编码,实现即攻击,但这是一个非常有益的。这是可能的,它只有在古怪的模式。
Internet Explorer,野生动物园,铬及 歌剧 用户需要记住explicidly设置的行高价值CSS。我做的样式表组的初步建设所有文本框如下。
<style>
TEXTAREA { line-height: 14px; font-size: 12px; font-family: arial }
</style>
这里是一个功能我只是写在jQuery做的-你可以口到 原型, 但他们不支持"活动"初以元素添加了由阿贾克斯的请求不作出回应。
这个版本不仅扩大了,但它还合同时删除或退格被压下。
这个版本依赖于jQuery1.4.2.
享;)
使用:
$("#sometextarea").textareacontrol();
或者(任何jQuery选择的示例)
$("textarea").textareacontrol();
这是测试 Internet Explorer7/Internet Explorer8, 火狐3.5和铬。所有工作的罚款。
使用ASP.NET只需简单地这样做:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Automatic Resize TextBox</title>
<script type="text/javascript">
function setHeight(txtarea) {
txtarea.style.height = txtdesc.scrollHeight + "px";
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:TextBox ID="txtarea" runat= "server" TextMode="MultiLine" onkeyup="setHeight(this);" onkeydown="setHeight(this);" />
</form>
</body>
</html>