【问题标题】:Is there anyway to have a textarea "autofit" height based on the content at page load?无论如何,是否有基于页面加载内容的文本区域“自动调整”高度?
【发布时间】:2014-06-20 12:33:44
【问题描述】:

有没有通过 CSS 或 Javascript 根据内容设置 textarea 的高度?我的 CSS 中有一个硬编码的高度,但我希望它是默认值,所以页面加载时没有垂直滚动条?

【问题讨论】:

标签: javascript html css textarea


【解决方案1】:

http://www.jacklmoore.com/autosize/ 将 Autosize 拖放到任何网页中,它应该可以正常工作。如果您对它的工作原理感到好奇,源代码很短并且评论很好。

// Example:
$(document).ready(function(){
    $('textarea').autosize();   
});

来源:https://github.com/jackmoore/autosize

演示:http://www.jacklmoore.com/autosize/

【讨论】:

  • 这不仅仅是在页面加载时:它是动态的(尽管使用此插件可能会获得效果)。动态被问到:stackoverflow.com/questions/454202/…
  • 如果有人在安装 Autosize 时遇到问题,重要的 javascript 位于 raw.githubusercontent.com/jackmoore/autosize/master/dist/…。在项目中包含该脚本后,您只需将这行 javascript 也包含在项目中: autosize(document.querySelectorAll('textarea'))
  • 漂亮干净的脚本,易于使用,强烈推荐!
【解决方案2】:

您可以通过jQuery UI Autoresize 使用自动调整大小插件

这里是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>

这里是 jquery,

$('textarea').autoResize();

见DEMO

【讨论】:

  • 也许添加一个$('textarea').change() 来触发页面加载时的调整大小?问题希望页面加载时没有垂直滚动条,这可能意味着文本区域可能已预先填充。
【解决方案3】:

没有插件你可以做类似的事情

$(document).ready(function(){
  elem=document.getElementById('#elemid');
  while(elem.clientHeight < elem.scrollHeight) {elem.height(elem.height()+10)}
});

在文本区域有滚动条时调整其大小(因此 elem.clientHeight

没有测试代码,只是“概念”。

编辑:傻瓜,它更容易,没有循环......

if (elem.clientHeight < elem.scrollHeight) elem.style.height=elem.scrollHeight+"px";

【讨论】:

    【解决方案4】:

    在 chrome 中测试

    纯 javascript 解决方案(无插件,无 jquery)

    在行动:fiddle

    我创建了 3 个函数:

    • 获取行高
    • 获取行数
    • 在您键入时设置文本区域的高度(输入事件)

        //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);
    &lt;textarea id="ta"&gt;&lt;/textarea&gt;

    【讨论】:

      【解决方案5】:

      A nice solution

      JSFiddle

      HTML

      <div id="container">
          <textarea >
          1
          12
          123
          1234
          12345
          123456
          1234567
          </textarea>
      </div>
      

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

      【讨论】:

        【解决方案6】:

        这个other question about WhatsApp like input 被错误地标记为当前问题的重复。由于无法在那里回答,所以在这里回答。

        我试图创建一个类似于 WhatsApp 的输入区域,具有以下功能:

        1. 当内容超过 4em 时,div/textarea 应该向上扩展
        2. div/textarea 的最大高度应为 6em
        3. 消息区域(div/textarea 上方)应减小,即其滚动条图钉大小应更改。

        这是我的纯 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>

        【讨论】:

        • OP 询问的是 textarea,它与 contentEditable 不同。
        【解决方案7】:

        您可以使用 ExpandingTextArea 插件,其中在您的 textarea 后面维护一个不可见的克隆 pre 元素。每当此 pre 的高度发生变化时,都会更新 textarea。

        很简单,只需在页面中包含 "expanding.js" 和 "jQuery" 并将“expanding”类添加到文本区域你需要扩展的地方。

        <script src='expanding.js'></script>
        <textarea class='expanding'></textarea>
        

        关注the link了解更多详情和演示

        注意:它适用于已添加文本的文档加载

        【讨论】:

        • @leora,你对上面的解释没意见。它可能是您正在寻找的必需品。 :)
        【解决方案8】:

        如果您不介意文本区域内的 scollbar,您可以使用

        $(document).ready(function(){
            tx = $('#textarea')
            tx.height(tx.prop('scrollHeight'));
        
        })
        

        这是Fiddle

        另一个Fiddle 设置了最小和最大宽度。

        但是有像auto-size这样的插件

        文本框的高度随着输入而增加。

        或者你可以试试这个plug-in

        【讨论】:

          【解决方案9】:

          这是一个纯 JavaScript 解决方案。没有 jquery,没有插件等。DEMO

          那么它是如何工作的呢?假设您有默认字体大小/行高/等。好吧,您的 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;
          }
          

          然后..

              var selector = document.getElementsByClassName('textarea');
              for(var i = 0; i < selector.length; i++)
              {
                  selector[i].onkeyup = function(){
                      textareaSetSize(this, 400);
                  };   
              }
          

          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>
          

          运行它...

          textareaSetSize(ta, 500);
          textareaSetSize(ta2, 400);
          textareaSetSize(ta3, 400);
          textareaSetSize(ta4, 400);
          

          这不是一个完美的解决方案,所以如果您看到创新,请告诉我。

          【讨论】:

            【解决方案10】:

            我在textarea下面使用的唯一css是它的width,不需要设置初始height。 overflow 也不需要,因为将使用的 scrollHeight 是:

            元素内容高度的度量,包括内容 由于溢出,在屏幕上不可见。

            scrollHeight:MDN

            如果您想使用 Internet Explorer,则必须使用 overflow: auto,否则 IE 坚持要添加垂直滚动条(即使没有可滚动的内容)。

            请注意,width 也不需要指定,但它是与此主题相关的最常用设置的属性。

            这是所需的 JavaScript:

            document.addEventListener("DOMContentLoaded", function(event) {
                var ta = document.getElementById('ta');
                ta.style.height = ta.scrollHeight + 'px';
            });
            

            当 DOM 加载完毕后,textarea 的height 被设置为它的scrollHeight。

            这是一个完整的测试页面:

            <!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>
            

            如果需要,代码可以应用于页面上的所有文本区域:

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

            【讨论】:

              【解决方案11】:

              我不知道为什么,但似乎我的搜索引擎为我带来了另一种解决方案(“操作方法”教程):

              http://www.sitepoint.com/build-auto-expanding-textarea-3/

              编辑:

              这里是代码..

              /**
               * TextAreaExpander plugin for jQuery
               * v1.0
               * Expands or contracts a textarea height depending on the
               * quatity of content entered by the user in the box.
               *
               * By Craig Buckler, Optimalworks.net
               *
               * As featured on SitePoint.com:
               * http://www.sitepoint.com/blogs/2009/07/29/build-auto-expanding-textarea-1/
               *
               * Please use as you wish at your own risk.
               */
              
              /**
               * Usage:
               *
               * From JavaScript, use:
               *     $(<node>).TextAreaExpander(<minHeight>, <maxHeight>);
               *     where:
               *       <node> is the DOM node selector, e.g. "textarea"
               *       <minHeight> is the minimum textarea height in pixels (optional)
               *       <maxHeight> is the maximum textarea height in pixels (optional)
               *
               * Alternatively, in you HTML:
               *     Assign a class of "expand" to any <textarea> tag.
               *     e.g. <textarea name="textarea1" rows="3" cols="40" class="expand"></textarea>
               *
               *     Or assign a class of "expandMIN-MAX" to set the <textarea> minimum and maximum height.
               *     e.g. <textarea name="textarea1" rows="3" cols="40" class="expand50-200"></textarea>
               *     The textarea will use an appropriate height between 50 and 200 pixels.
               */
              
              (function($) {
              
                  // jQuery plugin definition
                  $.fn.TextAreaExpander = function(minHeight, maxHeight) {
              
                      var hCheck = !($.browser.msie || $.browser.opera);
              
                      // resize a textarea
                      function ResizeTextarea(e) {
              
                          // event or initialize element?
                          e = e.target || e;
              
                          // find content length and box width
                          var vlen = e.value.length, ewidth = e.offsetWidth;
                          if (vlen != e.valLength || ewidth != e.boxWidth) {
              
                              if (hCheck && (vlen < e.valLength || ewidth != e.boxWidth)) e.style.height = "0px";
                              var h = Math.max(e.expandMin, Math.min(e.scrollHeight, e.expandMax));
              
                              e.style.overflow = (e.scrollHeight > h ? "auto" : "hidden");
                              e.style.height = h + "px";
              
                              e.valLength = vlen;
                              e.boxWidth = ewidth;
                          }
              
                          return true;
                      };
              
                      // initialize
                      this.each(function() {
              
                          // is a textarea?
                          if (this.nodeName.toLowerCase() != "textarea") return;
              
                          // set height restrictions
                          var p = this.className.match(/expand(\d+)\-*(\d+)*/i);
                          this.expandMin = minHeight || (p ? parseInt('0'+p[1], 10) : 0);
                          this.expandMax = maxHeight || (p ? parseInt('0'+p[2], 10) : 99999);
              
                          // initial resize
                          ResizeTextarea(this);
              
                          // zero vertical padding and add events
                          if (!this.Initialized) {
                              this.Initialized = true;
                              $(this).css("padding-top", 0).css("padding-bottom", 0);
                              $(this).bind("keyup", ResizeTextarea).bind("focus", ResizeTextarea);
                          }
                      });
              
                      return this;
                  };
              
              })(jQuery);
              
              
              // initialize all expanding textareas
              jQuery(document).ready(function() {
                  jQuery("textarea[class*=expand]").TextAreaExpander();
              });
              

              我把 cmets 留在了代码中,因为这不是我的工作;)

              【讨论】:

                【解决方案12】:

                我无法使用scrollHeight,因为它在页面加载时返回 0(可能是因为我的 textarea 在加载时被隐藏了)。 可能不是嵌套练习(我是 js 的新手),但唯一有效的选择是计算 textarea 中的行数并获取其中较长行的长度。然后相应地设置width 和height。

                var elements = document.getElementsByTagName("textarea")
                for (var i = 0; i < elements.length; i++) {
                    var atagelement = elements[i];
                    console.log(atagelement.value);
                
                    var textareasplit =atagelement.value.split(/\r|\r\n|\n/);
                    var textareaheight =  textareasplit.length *17  // change 17 according to your needs
                
                    var maxline=0
                    for  (var j = 0; j < textareasplit.length; j++){
                    var line = textareasplit[j];
                    var linelenght= line.length;
                        if (maxline < linelenght){
                            maxline= linelenght;
                        };
                    };
                    var textareawidth= maxline*10  // change 10 according to your needs
                    atagelement.setAttribute('style', "width:" + textareawidth+"px ; height:"+textareaheight+"px");
                
                }
                

                如果需要,也可以这样设置max-width(或max-height)

                    var maxwidth= window.innerWidth *0.8
                    console.log(maxwidth)
                    atagelement.setAttribute('style', "width:" + textareawidth+"px ; height:"+textareaheight+"px ; max-width:" + maxwidth+ "px");
                

                【讨论】:

                  【解决方案13】:

                  这对我有用

                  $(function(){
                      $('body').on('keydown','textarea', function(event) {
                          if ($('textarea')[0].clientHeight < $('textarea')[0].scrollHeight)
                          {
                              $('textarea').css({'height': $('textarea')[0].scrollHeight+"px"});
                          }
                          else
                          {
                              // reset height to default value
                              $('textarea').css({'height': ''});
                          }
                      });
                  });
                  

                  【讨论】:

                    【解决方案14】:

                    我使用了 1 个简单的 JavaScript 函数和 2 个 CSS 类。

                    <style>
                        textarea{
                         height: auto;
                         resize: none;
                         overflow: auto;
                        }
                    
                        .disabled-input{
                         min-height: 4em;
                         }
                    </style>
                    
                    <script>
                        function objHeight( obj ){
                            /**
                             * Function to adjusting textareas height
                             */
                            obj.style.height = 'auto';
                            obj.style.height = obj.scrollHeight*1.1 + 'px';
                        }
                    </script>
                    

                    要实现它: objHeight(document.getElementById('YOUR_ELEMENT_ID');

                    【讨论】:

                      猜你喜欢
                      • 2020-12-10
                      • 1970-01-01
                      • 1970-01-01
                      • 1970-01-01
                      • 2011-08-04
                      • 2012-04-14
                      • 1970-01-01
                      • 1970-01-01
                      • 1970-01-01
                      相关资源
                      最近更新 更多