javascript textarea根据内容js或jquery设置高度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11698956/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 14:02:36  来源:igfitidea点击:

textarea set height based on content js or jquery

phpjavascriptjqueryhtml

提问by cppit

this is my code: (keep it simple)

这是我的代码:(保持简单)

<textarea style="height:100px;">
    $textareatext
</textarea>
  • if $textareatextis 1 line long I want the height of textarea to fit
  • if its 3, 5 or 10 lines...same thing.
  • 如果$textareatext是 1 行长,我希望 textarea 的高度适合
  • 如果它是 3、5 或 10 行......同样的事情。

The issue I am having is at 100pxthe height is too big, but if I set it to 20pxand there are 10 lines then the textarea height is too small. NOTE: values are preloaded via mysql. so I think it should count the lines,then set the height based on how many lines ? Any suggestions?

我遇到的问题是100px高度太大,但如果我将其设置为20px并且有 10 行,则 textarea 高度太小。注意:值是通过 mysql 预加载的。所以我认为它应该计算行数,然后根据多少行设置高度?有什么建议?

I use Javascript and jQuery, or anything you would suggest.

我使用 Javascript 和 jQuery,或者任何你会建议的东西。

Thank you.

谢谢你。

回答by TheCarver

These may help. They're both jQuery plugins.

这些可能会有所帮助。它们都是 jQuery 插件。

Edit

编辑

var $textArea = $("#textarea-container");

resizeTextArea($textArea);

$textArea.off("keyup.textarea").on("keyup.textarea", function() {
    resizeTextArea($(this));
});

function resizeTextArea($element) {
    $element.height($element[0].scrollHeight);
}?

This answer was provided by Fran?ois Wahl, below.

下面的 Fran?ois Wahl 提供了这个答案。

回答by Nope

Remove the hard-coded height and give your textareaan id:

删除硬编码的高度并给你textarea一个 id:

<textarea id="textarea-container">
    Line 1
    Line 2
    Line 3
    Line 4
</textarea>?

Using jQuery you can use the following to auto-resize at page load and then on the keuUpevent as previously mentioned.

使用 jQuery,您可以使用以下内容在页面加载时自动调整大小,然后在keuUp前面提到的事件上自动调整大小。

var $textArea = $("#textarea-container");

// Re-size to fit initial content as it is pre-loaded.
resizeTextArea($textArea);

// Remove this binding if you don't want to re-size on typing.
$textArea.off("keyup.textarea").on("keyup.textarea", function() {
    resizeTextArea($(this));
});

function resizeTextArea($element) {
    $element.height($element[0].scrollHeight);
}?

See DEMO

演示

Alternatively if all you care about is displaying it and removing the default row padding use this:

或者,如果您只关心显示它并删除默认行填充,请使用以下命令:

var $textArea = $("#textarea-container");
var nativeRowPadding = 15;

// Re-size to fit initial content.
resizeTextArea($textArea);

function resizeTextArea($element) {
    $element.height($element[0].scrollHeight-nativeRowPadding );
}?

See DEMO

演示

回答by patrick

To make sure all your textareas keep up with their contents, increasing or decreasing height as you type, use the following:

要确保您的所有 textarea 跟上它们的内容,在您键入时增加或减少高度,请使用以下内容:

$("textarea").on("input",function(){
   $(this).height("auto").height($(this)[0].scrollHeight);
}

it would actually be helpful to install this line of code on SO itself :)

在 SO 本身上安装这行代码实际上会很有帮助:)

回答by patrick

I made a OOP solution I use a lot:

我做了一个我经常使用的 OOP 解决方案:

$.fn.elasticHeight = function(){
    $( this ).height( 'auto' ).height( $( this )[ 0 ].scrollHeight );
    $( this ).on( "input", function(){
        $( this ).height( 'auto' ).height( $( this )[ 0 ].scrollHeight );
    } );
    return this;
};

then you just add the elasticHeight to your textarea like so:

然后您只需将 elasticHeight 添加到您的 textarea 中,如下所示:

$( "textarea" ).elasticHeight();

the return thisis to make it bubble... so you can do this:

return this是让泡沫...所以你可以这样做:

$( "textarea" ).elasticHeight().val( "default value" );

No need for fancy 3rd party plugins...

不需要花哨的第 3 方插件...

回答by Shrey Gupta

Hey just the following 5 lines of code did the job for preloaded textareas

嘿,以下 5 行代码完成了预加载文本区域的工作

window.onload= function(){

    var inputs, index;

    inputs = document.getElementsByTagName('textarea');

    for (index = 0; index < inputs.length; ++index) 
    {
    inputs[index].style.height=inputs[index].scrollHeight + 5
    }

}

回答by Nicholas.V

Multiple textarea support. Based off @Fran?ois answer. Demo Fiddle

多个 textarea 支持。基于@Fran?ois 的回答。演示小提琴

if ($(".textarea").length > 0) {
    $(".textarea").each(function () {
        resizeTextArea($(this));
        $(this).off("keyup.textarea").on("keyup.textarea", function () {
            resizeTextArea($(this));
        });
    });
}

function resizeTextArea($element) {
    $element.height($element[0].scrollHeight);
}

回答by spaceman12

<textarea id='myText'></textarea>

var obj=document.getElementById('myText');
obj.onkeyup=function(){
if(obj.scrollHeight>obj.offsetHeight)obj.style.height=obj.scrollHeight+'px';
}

I presume the user is typing into the textarea

我认为用户正在输入文本区域

回答by ekashking

Most solutions are either not increasing AND decreasing the textareaheight, OR too jumpy when you hit "Enter" to get to the next line, OR they are NOT working properly when the textareaheight goes off the browser window limits.

大多数解决方案要么不增加和减少textarea高度,要么在您点击“Enter”进入下一行时过于跳跃,或者当textarea高度超出浏览器窗口限制时它们无法正常工作。

Here is mine (Firefox, Chrome, Safari, Opera):

这是我的(Firefox、Chrome、Safari、Opera):

$('.textareaInput').on('input', function(e) {
   if ($(this).outerHeight() > 162) {
       while($(this).outerHeight() < this.scrollHeight) {
           $(this).height($(this).height()+1);
       };

       while($(this).outerHeight() > this.scrollHeight) {
           $(this).height($(this).height()-1);
       };   

   } else {
       while($(this).outerHeight() < this.scrollHeight) {
           if ($(this).height())
           $(this).height($(this).height()+1);
       };
   }
});

... where 162 = 150(min-height) + 6(top padding) + 6(bottom padding):

... 其中 162 = 150(min-height) + 6(top padding) + 6(bottom padding):

.textareaInput {
    min-height:150px;
    padding: 6px 4px;
    overflow-y:hidden;    
}

回答by John Binary

The accepted code by Fran?ois Wahl does not work when you are deleting lines in textarea - the height stays the same. Make sure you make textarea's height "auto" before getting it's scrollHeight:

当您删除 textarea 中的行时,Fran?ois Wahl 接受的代码不起作用 - 高度保持不变。确保在获取它的 scrollHeight 之前使 textarea 的高度为“自动”:

function resizeTextArea($element) {
    $element.height("auto");
    $element.height($element[0].scrollHeight);
}