【问题标题】:textarea set height based on content js or jquerytextarea根据内容js或jquery设置高度
【发布时间】:2012-07-28 06:47:39
【问题描述】:

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

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

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

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

谢谢。

【问题讨论】:

标签: php javascript jquery html


【解决方案1】:

这些可能会有所帮助。它们都是 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çois Wahl 提供。

【讨论】:

  • 页面加载完成后需要调整大小。变量 $textareatext 是从数据库中读取的。我知道如何在我输入后调整它的大小,有插件用于此
  • @PaparazzoKid: $("#myTArea").height($("#myTArea")[0].scrollHeight-15); 应该每次都可以工作,无论您从多少行开始。我认为不需要自己计算。
  • @FrançoisWahl:我认为你是对的。我的数学显然是大便。如果fossy回来,希望他会交换答案。我会解决这个问题,但你的代码更少。
  • @PaparazzoKid:不用担心,我不担心选择的答案,如果你想随时使用 jQuery + scrollHeight 更新你的答案,如果它有效,很酷,这是主要的: )
  • 这很奇怪。我提醒 textarea 值(比如 784),我提醒 textarea cols(比如 30),进行除法,我得到 26.1。我使用 Math.floor 将其降低到 26。应该是对的,不是吗?但事实并非如此,它比应有的多 5 行。无论如何,是的,我会用 scrollHeight 版本更新答案。谢谢。
【解决方案2】:

删除硬编码的高度并给你的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

【讨论】:

    【解决方案3】:

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

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

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

    【讨论】:

      【解决方案4】:

      嘿,以下 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
          }
      
      }
      

      【讨论】:

        【解决方案5】:

        多个文本区域支持。基于@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);
        }
        

        【讨论】:

          【解决方案6】:

          我做了一个我经常使用的 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" ).elasticHeight();
          

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

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

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

          【讨论】:

            【解决方案7】:

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

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

            【讨论】:

              【解决方案8】:

              大多数解决方案要么不增加和减少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】:
                <textarea id='myText'></textarea>
                
                var obj=document.getElementById('myText');
                obj.onkeyup=function(){
                if(obj.scrollHeight>obj.offsetHeight)obj.style.height=obj.scrollHeight+'px';
                }
                

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

                【讨论】:

                • 值是通过mysql预加载的
                【解决方案10】:

                const textarea = document.querySelector('textarea');
                
                function updateHeight(el) {
                  el.style.height = '';
                  el.style.height = el.scrollHeight + 'px';
                }
                
                updateHeight(textarea);
                
                textarea.addEventListener('input', () => updateHeight(textarea));
                &lt;textarea&gt;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?&lt;/textarea&gt;

                【讨论】:

                  猜你喜欢
                  • 1970-01-01
                  • 1970-01-01
                  • 2013-11-22
                  • 2015-03-04
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 2011-02-08
                  • 2016-06-03
                  相关资源
                  最近更新 更多