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

时间:2012-07-28 06:47:40

标签: php javascript jquery html

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

<textarea style="height:100px;">
    $textareatext
</textarea>
  • 如果$textareatext长1行,我希望textarea的高度适合
  • 如果它的3,5或10行......同样的事情。

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

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

谢谢。

10 个答案:

答案 0 :(得分:9)

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

修改

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

resizeTextArea($textArea);

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

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

这个答案由下面的FrançoisWahl提供。

答案 1 :(得分:8)

删除硬编码的高度,并为textarea提供一个ID:

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

使用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);
}​

请参阅DEMO

或者,如果你关心的只是显示它并删除默认的行填充,请使用:

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

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

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

请参阅DEMO

答案 2 :(得分:3)

要确保所有textareas都能跟上其内容,在键入时增加或减少高度,请使用以下内容:

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

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

答案 3 :(得分:1)

多个textarea支持。基于@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);
}

答案 4 :(得分:0)

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

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

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

我认为用户正在输入textarea

答案 5 :(得分:0)

嘿,只有以下5行代码完成了预装textareas的工作

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
    }

}

答案 6 :(得分:0)

当你在textarea中删除行时,FrançoisWahl接受的代码不起作用 - 高度保持不变。确保在获得它的scrollHeight之前让textarea的高度为“auto”:

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

答案 7 :(得分:0)

我制作了一个我经常使用的OOP解决方案,也许它可以帮助其他人:

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

然后你只需将elasticHeight添加到textarea中就像这样:

$( "textarea" ).elasticHeight();

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

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

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

答案 8 :(得分:0)

大多数解决方案要么不增加也不要降低textarea高度,要么在点击“Enter”以进入下一行时太急动,或者当textarea高度变为高时,它们无法正常工作关闭浏览器窗口限制。

这是我的(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);
       };
   }
});

...其中162 = 150(最小高度)+6(顶部填充)+6(底部填充):

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

答案 9 :(得分:0)

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>