javascript 是否有基于页面加载时的内容的文本区域“自动调整”高度?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23451611/
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
Is there anyway to have a textarea "autofit" height based on the content at page load?
提问by leora
Is there anyway through CSS or Javascript set the height of the textarea based on the content? I have a hardcoded height in my CSS but i wanted it to default so there is no vertical scroll bar on page load?
无论如何通过CSS或Javascript根据内容设置textarea的高度?我的 CSS 中有一个硬编码的高度,但我希望它是默认的,所以页面加载时没有垂直滚动条?
采纳答案by MK.
How about http://www.Hymanlmoore.com/autosize/Drop Autosize into any web page and it should Just Work. The source is short and well commented if you are curious to how it works.
如何http://www.Hymanlmoore.com/autosize/跌落自动调整到任何网页,它应该只是工作。如果您对它的工作原理感到好奇,那么源代码很短而且评论很好。
// Example:
$(document).ready(function(){
$('textarea').autosize();
});
Source: https://github.com/Hymanmoore/autosize
来源:https: //github.com/Hymanmoore/autosize
回答by mcn
You can use the auto resize plugin using the jQuery UI Autoresize
您可以使用jQuery UI Autoresize使用自动调整大小插件
Here is the html,
这是html,
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script
src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>
<script src="http://css-tricks.com/examples/TextareaTricks/js/autoresize.jquery.min.js"></script>
<textarea></textarea>
and here is the jquery,
这是jquery,
$('textarea').autoResize();
see DEMO
看演示
回答by miguel-svq
Without plugins you could do something like
没有插件你可以做类似的事情
$(document).ready(function(){
elem=document.getElementById('#elemid');
while(elem.clientHeight < elem.scrollHeight) {elem.height(elem.height()+10)}
});
Resizing the textarea while it does have a scrollbar (so elem.clientHeight < elem.scrollHeight). You can do it quite easily even without JQuery, in plain javascript.
在 textarea 有滚动条时调整它的大小(所以 elem.clientHeight < elem.scrollHeight)。即使没有 JQuery,您也可以使用纯 JavaScript 轻松完成。
Didn't test the code, it's just the "concept".
没有测试代码,它只是“概念”。
EDIT: Dumb me, it's much easier, no loops...
编辑:愚蠢的我,它更容易,没有循环......
if (elem.clientHeight < elem.scrollHeight) elem.style.height=elem.scrollHeight+"px";
回答by Amro
Tested in chrome
在铬中测试
Pure javascript solution(No plugin, No jquery)
纯 javascript 解决方案(无插件,无 jquery)
in action: fiddle
在行动:小提琴
I created 3 functions:
我创建了 3 个函数:
- get line height
- get number of lines
- set the height of textarea as you type (input event)
- 获取行高
- 获取行数
- 输入时设置 textarea 的高度(输入事件)
//attach input event
document.getElementById('ta').addEventListener('input', autoHeight, false);
function autoHeight(e){
var lh = getLineHeightInPixels(e.target);
var nol = getNumberOfLines(e.target);
var ht = lh * nol;
e.target.style.height = ht + 'px';
}
function getNumberOfLines(el){
var text = el.value
var lines = text.split(/\r|\r\n|\n/);
return lines.length;
}
function getLineHeightInPixels(el){
var tempDiv = document.createElement('div');
tempDiv.style.visibility = 'hidden';
tempDiv.style.fontFamily = getComputedStyle(el).getPropertyValue('font-family');
tempDiv.style.fontSize = getComputedStyle(el).getPropertyValue('font-size');
tempDiv.style.lineHeight = getComputedStyle(el).getPropertyValue('line-height');
tempDiv.style.fontVariant = getComputedStyle(el).getPropertyValue('font-variant');
tempDiv.style.fontStyle = getComputedStyle(el).getPropertyValue('font-style');
tempDiv.innerText = 'abcdefghijklmnopqrstuwxyz';
document.documentElement.appendChild(tempDiv);
var ht = parseInt(getComputedStyle(tempDiv).getPropertyValue('height'))
document.documentElement.removeChild(tempDiv);
return (ht);
}
//set height on document load
document.addEventListener('DOMContentLoaded', function(){document.getElementById('ta').style.height = getLineHeightInPixels(document.getElementById('ta')) + 'px';}, false);
<textarea id="ta"></textarea>
回答by Itay Gal
HTML
HTML
<div id="container">
<textarea >
1
12
123
1234
12345
123456
1234567
</textarea>
</div>
CSS
CSS
div#container textarea {
overflow-y: hidden; /* prevents scroll bar flash */
padding-top: 1.1em; /* prevents text jump on Enter keypress */
}
JQuery
查询
// auto adjust the height of
$('#container').on( 'keyup', 'textarea', function (e){
$(this).css('height', 'auto' );
$(this).height( this.scrollHeight );
});
$('#container').find( 'textarea' ).keyup();
回答by kemicofa ghost
Here is a pure javascript solution. No jquery, no plugins, etc.. DEMO
这是一个纯javascript解决方案。没有jquery,没有插件等。DEMO
So how does it work? Suppose you have a default font size/line-height/etc. Well your textarea holds around 11 characters per 100px width. If we can keep this in mind then we can use this function.
那么它是怎样工作的?假设你有一个默认的字体大小/行高/等。那么你的 textarea 每 100px 宽度可以容纳大约 11 个字符。如果我们能记住这一点,那么我们就可以使用这个函数。
function textareaSetSize(elem, width)
{
var length = elem.value.length;
//about 11 characters per 100 pixels
var estimatedLines = Math.round(length/(width/100*11));
//alert('Estimated number of lines: ' + length);
elem.style.width = width + 'px';
elem.rows = estimatedLines;
}
Then..
然后..
var selector = document.getElementsByClassName('textarea');
for(var i = 0; i < selector.length; i++)
{
selector[i].onkeyup = function(){
textareaSetSize(this, 400);
};
}
html...
html...
<button id="reset">Empty</button>
<textarea class="textarea" id="autosize"></textarea>
<textarea class="textarea" id="autosize2"></textarea>
<textarea class="textarea" id="autosize3"></textarea>
<textarea class="textarea" id="autosize4"></textarea>
runnning it...
运行它...
textareaSetSize(ta, 500);
textareaSetSize(ta2, 400);
textareaSetSize(ta3, 400);
textareaSetSize(ta4, 400);
This isn't a perfect solution, so if you see an innovation let me know.
这不是一个完美的解决方案,所以如果你看到创新,请告诉我。
回答by Kaya Toast
This other question about WhatsApp like inputhas been incorrectly marked as a duplicate of this current question. As I cannot answer there, I'm answering it here.
这就像输入有关的WhatsApp等问题被错误地标记为这个当前问题的一个副本。由于我无法在那里回答,所以我在这里回答。
I was trying to create a WhatsApp like input area, with the following features:
我试图创建一个类似 WhatsApp 的输入区域,具有以下功能:
- The div/textarea should expand upwards when the content exceeds 4em
- Max height of the div/textarea should be 6em
- The messaging area (above the div/textarea) should reduce i.e. its scrollbar thumbtack size should change.
- 当内容超过 4em 时,div/textarea 应该向上扩展
- div/textarea 的最大高度应该是 6em
- 消息区域(在 div/textarea 上方)应该减少,即它的滚动条图钉大小应该改变。
Here is my pure CSS solution, if anyone is looking for it (like I was a few minutes ago).
这是我的纯 CSS 解决方案,如果有人正在寻找它(就像我几分钟前一样)。
.arena {
position: absolute;
height: 20em;
width: 12em;
background-color: #efefef;
padding: 1em;
display: flex;
flex-direction: column;
justify-content: space-between;
}
.messages {
padding: 0.2em;
height: 5em;
flex: 1 1 0;
overflow: auto;
}
.content {
background-color: teal;
height: 20em;
}
.footer {
position: relative;
background-color: #cdcdcd;
padding: 0.2em;
}
.editable {
outline: none;
max-height: 6em;
min-height: 4em;
overflow: auto;
width: 80%;
background-color: #fff;
}
<div class="arena">
<div class="messages">
<div class="content"></div>
</div>
<div class="footer">
<div class="editable" contenteditable="true"></div>
</div>
</div>
回答by Sudheer
If you dont mind a scollbar inside the text area you can use
如果您不介意文本区域内的 scollbar,您可以使用
$(document).ready(function(){
tx = $('#textarea')
tx.height(tx.prop('scrollHeight'));
})
and here is a Fiddle
这是一个小提琴
another Fiddlethis has min and max-width set.
另一个Fiddle设置了最小和最大宽度。
but with plug-ins like auto-size
但是使用自动调整大小之类的插件
the height of the text box increases with input.
文本框的高度随着输入而增加。
or you can try this plug-in
或者你可以试试这个插件
回答by Andy G
The only css I use below on the textarea
is its width
, there is no need to set an initial height
. overflow
should not be needed either as the scrollHeight
that will be used is:
我在下面使用的唯一 csstextarea
是它的width
,不需要设置初始height
. overflow
也不需要,因为scrollHeight
将使用的是:
a measurement of the height of an element's content including content not visible on the screen due to overflow.
对元素内容高度的测量,包括由于溢出而在屏幕上不可见的内容。
scrollHeight:MDN
滚动高度:MDN
If you want to work with Internet Explorer though, then it is necessary to use overflow: auto
as otherwise IE insists on adding a vertical scrollbar (even though there is nothing to scroll).
如果您想使用 Internet Explorer,则必须使用overflow: auto
,否则 IE 会坚持添加垂直滚动条(即使没有可滚动的内容)。
Note that the width
does not need to be specified either, but it is the property that is most commonly set in relation to this topic.
请注意,width
也不需要指定 ,但它是与此主题相关的最常设置的属性。
This is the JavaScript needed:
这是所需的 JavaScript:
document.addEventListener("DOMContentLoaded", function(event) {
var ta = document.getElementById('ta');
ta.style.height = ta.scrollHeight + 'px';
});
When the DOM has loaded the height
of the textarea is set to its scrollHeight
.
当 DOM 加载height
时,textarea 的 设置为它的scrollHeight
.
Here is a complete page for testing:
这是一个完整的测试页面:
<!DOCTYPE html>
<html>
<head>
<title>Some Title</title>
<style>
textarea {
width: 300px;
overflow: auto;
}
</style>
</head>
<body>
<textarea id="ta">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</textarea>
<script>
document.addEventListener("DOMContentLoaded", function(event) {
var ta = document.getElementById('ta');
ta.style.height = ta.scrollHeight + 'px';
});
</script>
</body>
</html>
If required, the code can be applied to all textareas on the page:
如果需要,代码可以应用于页面上的所有文本区域:
document.addEventListener("DOMContentLoaded", function(event) {
var tas = document.getElementsByTagName('textarea');
for (var i=0; i < tas.length; i++) {
tas[i].style.height = tas[i].scrollHeight + 'px';
}
});
回答by Mazzu
Hey can go with ExpandingTextArea plugin in which an invisible clone pre element is maintained behind your textarea. Whenever the height of this pre changes, the textarea is updated.
嘿,可以使用 ExpandingTextArea 插件,其中在 textarea 后面维护一个不可见的克隆 pre 元素。每当这个 pre 的高度发生变化时,textarea 就会更新。
It is simple just include "expanding.js"and "jQuery"in your page and add class "expanding" to the textareato which u need to expand.
很简单,只需在您的页面中包含“expanding.js”和“jQuery”,并将类“expanding”添加到您需要扩展的文本区域。
<script src='expanding.js'></script>
<textarea class='expanding'></textarea>
Follow the linkfor more details and Demo
按照该链接的更多细节和演示
Note:It will work on document load for already added texts
注意:它适用于已添加文本的文档加载