简体   繁体   English

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

[英]textarea set height based on content js or jquery

this is my code: (keep it simple)这是我的代码:(保持简单)

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

The issue I am having is at 100px the height is too big, but if I set it to 20px and there are 10 lines then the textarea height is too small.我遇到的问题是100px高度太大,但如果我将它设置为20px并且有 10 行,那么 textarea 高度太小。 NOTE: values are preloaded via mysql.注意:值是通过 mysql 预加载的。 so I think it should count the lines,then set the height based on how many lines?所以我认为它应该计算行数,然后根据多少行设置高度? Any suggestions?有什么建议么?

I use Javascript and jQuery, or anything you would suggest.我使用 Javascript 和 jQuery,或者您建议的任何东西。

Thank you.谢谢你。

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 提供,如下所示。

Remove the hard-coded height and give your textarea an 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 keuUp event 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演示

To make sure all your textareas keep up with their contents, increasing or decreasing height as you type, use the following:要确保所有文本区域都与其内容保持一致,在您键入时增加或减少高度,请使用以下内容:

$("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 本身上安装这行代码实际上会很有帮助:)

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
    }

}

Multiple textarea support.多文本区域支持。 Based off @François answer.基于@François 的回答。 Demo Fiddle演示小提琴

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);
}

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" ).elasticHeight();

the return this is to make it bubble... so you can do this: return this是让它起泡......所以你可以这样做:

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

No need for fancy 3rd party plugins...不需要花哨的第 3 方插件......

 const textarea = document.querySelector('textarea'); function updateHeight(el) { el.style.height = ''; el.style.height = el.scrollHeight + 'px'; } updateHeight(textarea); textarea.addEventListener('input', () => updateHeight(textarea));
 <textarea>Lorem ipsum dolor sit amet consectetur adipisicing elit. Qui, id? Aut dolorem nam iste. Asperiores minima nemo porro autem quidem. Quae quas dolore possimus sunt vitae quo ea incidunt. Sit repellendus at consequuntur fugiat quos, quisquam atque dolorem ipsa autem iure quod? Expedita eius cum asperiores obcaecati eaque laudantium libero aliquid ex doloremque modi incidunt, officiis velit reiciendis cupiditate necessitatibus harum quod repellendus officia quidem. Aliquid, temporibus. Nihil error cumque labore eius voluptas commodi accusamus eaque distinctio, facere dolores, Laudantium distinctio a quisquam quibusdam error nam quia ex cupiditate? fuga saepe maiores cumque enim corporis alias itaque recusandae vel! Omnis?</textarea>

<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我假设用户正在输入文本区域

The accepted code by François Wahl does not work when you are deleting lines in textarea - the height stays the same.当您删除 textarea 中的行时,François Wahl 接受的代码不起作用 - 高度保持不变。 Make sure you make textarea's height "auto" before getting it's scrollHeight:确保在获取 scrollHeight 之前将 textarea 的高度设置为“自动”:

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

Most solutions are either not increasing AND decreasing the textarea height, OR too jumpy when you hit "Enter" to get to the next line, OR they are NOT working properly when the textarea height 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(最小高度)+ 6(顶部填充)+ 6(底部填充):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM