如何使用Prototype自动调整textarea?

时间:2008-08-11 01:43:13

标签: javascript html css textarea prototypejs

我目前正在为我工​​作的公司开发一个内部销售应用程序,我有一个允许用户更改收货地址的表单。

现在我觉得它看起来会更好,如果我用于主要地址详细信息的textarea只占用其中文本的区域,并在文本被更改时自动调整大小。

这是目前的截图。

ISO Address

有什么想法吗?


@克里斯

一个好点,但有理由我希望它调整大小。我希望它占用的区域是其中包含的信息区域。正如你在屏幕截图中看到的那样,如果我有一个固定的textarea,它会占用相当大的垂直空间。

我可以减少字体,但我需要地址大而且可读。现在我可以减小文本区域的大小,但是我遇到了地址行需要3或4(一行需要5行)的人的问题。需要让用户使用滚动条是一个主要的禁忌。

我想我应该更具体一点。我正在垂直调整大小,宽度无关紧要。与此相关的唯一问题是,当窗口宽度太小时,ISO编号(大“1”)会被推到地址下面(如截图所示)。

这不是要有一个gimick;它是关于有一个用户可以编辑的文本字段,它不会占用不必要的空间,但会显示其中的所有文本。

虽然如果有人想出另一种解决问题的方法,我也会对此持开放态度。


我稍微修改了代码,因为它的行为有点奇怪。我将其更改为在keyup上激活,因为它不会考虑刚刚输入的字符。

resizeIt = function() {
  var str = $('iso_address').value;
  var cols = $('iso_address').cols;
  var linecount = 0;

  $A(str.split("\n")).each(function(l) {
    linecount += 1 + Math.floor(l.length / cols); // Take into account long lines
  })

  $('iso_address').rows = linecount;
};

18 个答案:

答案 0 :(得分:72)

当你在人们的墙上写字时,Facebook会这么做,但只会垂直调整大小。

由于自动换行,长行等等,水平调整大小让我觉得一团糟,但垂直调整大小似乎非常安全和漂亮。

我所知道的Facebook使用新手都没有提及任何有关它或被混淆的内容。我用这个作为轶事证据来说“继续,实施它”。

使用Prototype执行此操作的一些JavaScript代码(因为这是我所熟悉的):

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
  "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <script src="http://www.google.com/jsapi"></script>
        <script language="javascript">
            google.load('prototype', '1.6.0.2');
        </script>
    </head>

    <body>
        <textarea id="text-area" rows="1" cols="50"></textarea>

        <script type="text/javascript" language="javascript">
            resizeIt = function() {
              var str = $('text-area').value;
              var cols = $('text-area').cols;

              var linecount = 0;
              $A(str.split("\n")).each( function(l) {
                  linecount += Math.ceil( l.length / cols ); // Take into account long lines
              })
              $('text-area').rows = linecount + 1;
            };

            // You could attach to keyUp, etc. if keydown doesn't work
            Event.observe('text-area', 'keydown', resizeIt );

            resizeIt(); //Initial on load
        </script>
    </body>
</html>
PS:显然这个JavaScript代码非常幼稚而且没有经过充分测试,你可能不想在带有小说的文本框中使用它,但是你会得到一般的想法。

答案 1 :(得分:60)

对其中一些答案的一个改进是让CSS完成更多的工作。

基本路线似乎是:

  1. 创建一个容器元素来保存textarea和隐藏的div
  2. 使用Javascript,保持textarea的内容与div的同步
  3. 让浏览器完成计算div高度的工作
  4. 因为浏览器会处理隐藏div的渲染/大小调整,所以我们避免使用 明确设置textarea的身高。
  5. document.addEventListener('DOMContentLoaded', () => {
        textArea.addEventListener('change', autosize, false)
        textArea.addEventListener('keydown', autosize, false)
        textArea.addEventListener('keyup', autosize, false)
        autosize()
    }, false)
    
    function autosize() {
        // Copy textarea contents to div browser will calculate correct height
        // of copy, which will make overall container taller, which will make
        // textarea taller.
        textCopy.innerHTML = textArea.value.replace(/\n/g, '<br/>')
    }
    html, body, textarea {
        font-family: sans-serif;
        font-size: 14px;
    }
    
    .textarea-container {
        position: relative;
    }
    
    .textarea-container > div, .textarea-container > textarea {
        word-wrap: break-word; /* make sure the div and the textarea wrap words in the same way */
        box-sizing: border-box;
        padding: 2px;
        width: 100%;
    }
    
    .textarea-container > textarea {
        overflow: hidden;
        position: absolute;
        height: 100%;
    }
    
    .textarea-container > div {
        padding-bottom: 1.5em; /* A bit more than one additional line of text. */ 
        visibility: hidden;
        width: 100%;
    }
    <div class="textarea-container">
        <textarea id="textArea"></textarea>
        <div id="textCopy"></div>
    </div>

答案 2 :(得分:38)

这是另一种自动调整textarea的技术。

  • 使用像素高度而不是行高:如果使用比例字体,则更准确地处理换行。
  • 接受ID或元素作为输入
  • 接受可选的最大高度参数 - 如果您不希望文本区域超出一定大小(将其全部保留在屏幕上,避免破坏布局等),则非常有用。
  • 在Firefox 3和Internet Explorer 6
  • 上测试过

<强>代码: (普通的香草JavaScript)

function FitToContent(id, maxHeight)
{
   var text = id && id.style ? id : document.getElementById(id);
   if (!text)
      return;

   /* Accounts for rows being deleted, pixel value may need adjusting */
   if (text.clientHeight == text.scrollHeight) {
      text.style.height = "30px";
   }

   var adjustedHeight = text.clientHeight;
   if (!maxHeight || maxHeight > adjustedHeight)
   {
      adjustedHeight = Math.max(text.scrollHeight, adjustedHeight);
      if (maxHeight)
         adjustedHeight = Math.min(maxHeight, adjustedHeight);
      if (adjustedHeight > text.clientHeight)
         text.style.height = adjustedHeight + "px";
   }
}

<强>演示: (使用jQuery,我正在输入的textarea上的目标 - 如果你安装了Firebug,将两个样本粘贴到控制台并在此页面上测试)

$("#post-text").keyup(function()
{
   FitToContent(this, document.documentElement.clientHeight)
});

答案 3 :(得分:12)

可能是最短的解决方案:

jQuery(document).ready(function(){
    jQuery("#textArea").on("keydown keyup", function(){
        this.style.height = "1px";
        this.style.height = (this.scrollHeight) + "px"; 
    });
});

这样你就不需要任何隐藏的div或类似的东西了。

注意:您可能需要使用this.style.height = (this.scrollHeight) + "px";,具体取决于您对textarea的样式(行高,填充和那种东西)。

答案 4 :(得分:8)

这是一个 Prototype 版本,用于调整文本区域的大小,该文本区域不依赖于textarea中的列数。这是一种优秀的技术,因为它允许您通过CSS控制文本区域以及具有可变宽度textarea。此外,此版本显示剩余的字符数。虽然没有要求,但这是一个非常有用的功能,如果不需要,可以轻松删除。

//inspired by: http://github.com/jaz303/jquery-grab-bag/blob/63d7e445b09698272b2923cb081878fd145b5e3d/javascripts/jquery.autogrow-textarea.js
if (window.Widget == undefined) window.Widget = {}; 

Widget.Textarea = Class.create({
  initialize: function(textarea, options)
  {
    this.textarea = $(textarea);
    this.options = $H({
      'min_height' : 30,
      'max_length' : 400
    }).update(options);

    this.textarea.observe('keyup', this.refresh.bind(this));

    this._shadow = new Element('div').setStyle({
      lineHeight : this.textarea.getStyle('lineHeight'),
      fontSize : this.textarea.getStyle('fontSize'),
      fontFamily : this.textarea.getStyle('fontFamily'),
      position : 'absolute',
      top: '-10000px',
      left: '-10000px',
      width: this.textarea.getWidth() + 'px'
    });
    this.textarea.insert({ after: this._shadow });

    this._remainingCharacters = new Element('p').addClassName('remainingCharacters');
    this.textarea.insert({after: this._remainingCharacters});  
    this.refresh();  
  },

  refresh: function()
  { 
    this._shadow.update($F(this.textarea).replace(/\n/g, '<br/>'));
    this.textarea.setStyle({
      height: Math.max(parseInt(this._shadow.getHeight()) + parseInt(this.textarea.getStyle('lineHeight').replace('px', '')), this.options.get('min_height')) + 'px'
    });

    var remaining = this.options.get('max_length') - $F(this.textarea).length;
    this._remainingCharacters.update(Math.abs(remaining)  + ' characters ' + (remaining > 0 ? 'remaining' : 'over the limit'));
  }
});

通过调用new Widget.Textarea('element_id')创建小部件。可以通过将它们作为对象传递来覆盖默认选项,例如, new Widget.Textarea('element_id', { max_length: 600, min_height: 50})。如果要为页面上的所有textareas创建它,请执行以下操作:

Event.observe(window, 'load', function() {
  $$('textarea').each(function(textarea) {
    new Widget.Textarea(textarea);
  });   
});

答案 5 :(得分:7)

以下是JQuery的解决方案:

$(document).ready(function() {
    var $abc = $("#abc");
    $abc.css("height", $abc.attr("scrollHeight"));
})

abcteaxtarea

答案 6 :(得分:5)

检查以下链接: http://james.padolsey.com/javascript/jquery-plugin-autoresize/

$(document).ready(function () {
    $('.ExpandableTextCSS').autoResize({
        // On resize:
        onResize: function () {
            $(this).css({ opacity: 0.8 });
        },
        // After resize:
        animateCallback: function () {
            $(this).css({ opacity: 1 });
        },
        // Quite slow animation:
        animateDuration: 300,
        // More extra space:
        extraSpace:20,
        //Textarea height limit
        limit:10
    });
});

答案 7 :(得分:3)

我做了一件非常容易的事情。首先,我将TextArea放入DIV中。其次,我已经为这个脚本调用了ready函数。

<div id="divTable">
  <textarea ID="txt" Rows="1" TextMode="MultiLine" />
</div>

$(document).ready(function () {
  var heightTextArea = $('#txt').height();
  var divTable = document.getElementById('divTable');
  $('#txt').attr('rows', parseInt(parseInt(divTable .style.height) / parseInt(altoFila)));
});

简单。它是div渲染后的最大高度,除以一行的一个TextArea的高度。

答案 8 :(得分:3)

重新审视这个问题,我已经让它变得更整洁了(虽然Prototype / JavaScript上有一个装满瓶子的人会提出改进建议吗?)。

var TextAreaResize = Class.create();
TextAreaResize.prototype = {
  initialize: function(element, options) {
    element = $(element);
    this.element = element;

    this.options = Object.extend(
      {},
      options || {});

    Event.observe(this.element, 'keyup',
      this.onKeyUp.bindAsEventListener(this));
    this.onKeyUp();
  },

  onKeyUp: function() {
    // We need this variable because "this" changes in the scope of the
    // function below.
    var cols = this.element.cols;

    var linecount = 0;
    $A(this.element.value.split("\n")).each(function(l) {
      // We take long lines into account via the cols divide.
      linecount += 1 + Math.floor(l.length / cols);
    })

    this.element.rows = linecount;
  }
}

请致电:

new TextAreaResize('textarea_id_name_here');

答案 9 :(得分:2)

我自己需要这个功能,但是这里的所有功能都没有,因为我需要它们。

所以我使用了Orion的代码并对其进行了更改。

我添加了一个最小高度,因此在破坏时它不会太小。

function resizeIt( id, maxHeight, minHeight ) {
    var text = id && id.style ? id : document.getElementById(id);
    var str = text.value;
    var cols = text.cols;
    var linecount = 0;
    var arStr = str.split( "\n" );
    $(arStr).each(function(s) {
        linecount = linecount + 1 + Math.floor(arStr[s].length / cols); // take into account long lines
    });
    linecount++;
    linecount = Math.max(minHeight, linecount);
    linecount = Math.min(maxHeight, linecount);
    text.rows = linecount;
};

答案 10 :(得分:2)

就像@memical的回答一样。

但是我发现了一些改进。您可以使用jQuery height()函数。但请注意填充顶部和填充底部像素。否则你的textarea会变得太快。

$(document).ready(function() {
  $textarea = $("#my-textarea");

  // There is some diff between scrollheight and height:
  //    padding-top and padding-bottom
  var diff = $textarea.prop("scrollHeight") - $textarea.height();
  $textarea.live("keyup", function() {
    var height = $textarea.prop("scrollHeight") - diff;
    $textarea.height(height);
  });
});

答案 11 :(得分:2)

我的解决方案不使用jQuery(因为有时它们不一定是同一个东西)在下面。虽然它只在Internet Explorer 7进行了测试,但社区可以指出这是错误的所有原因:

textarea.onkeyup = function () { this.style.height = this.scrollHeight + 'px'; }

到目前为止,我真的很喜欢它的工作方式,而且我并不关心其他浏览器,所以我可能会将它应用到我所有的textareas:

// Make all textareas auto-resize vertically
var textareas = document.getElementsByTagName('textarea');

for (i = 0; i<textareas.length; i++)
{
    // Retain textarea's starting height as its minimum height
    textareas[i].minHeight = textareas[i].offsetHeight;

    textareas[i].onkeyup = function () {
        this.style.height = Math.max(this.scrollHeight, this.minHeight) + 'px';
    }
    textareas[i].onkeyup(); // Trigger once to set initial height
}

答案 12 :(得分:1)

Internet Explorer,Safari,Chrome和Opera用户需要记住在CSS中明确设置行高值。我做了一个样式表,为所有文本框设置初始属性,如下所示。

<style>
    TEXTAREA { line-height: 14px; font-size: 12px; font-family: arial }
</style>

答案 13 :(得分:1)

这是我刚刚在jQuery中编写的一个函数 - 你可以将它移植到Prototype,但它们不支持jQuery的“活跃性”,因此Ajax请求添加的元素不会响应。 / p>

此版本不仅可以扩展,还可以在按下删除或退格时收缩。

此版本依赖于jQuery 1.4.2。

享受;)

http://pastebin.com/SUKeBtnx

用法:

$("#sometextarea").textareacontrol();

或(例如任何jQuery选择器)

$("textarea").textareacontrol();

已在Internet Explorer 7 / Internet Explorer 8,Firefox 3.5和Chrome上进行了测试。一切正常。

答案 14 :(得分:1)

以下是Jeremy于6月4日发布的Prototype小部件的扩展:

如果您在textareas中使用限制,它会阻止用户输入更多字符。它会检查是否还有字符。如果用户将文本复制到文本区域,则文本将以最大值切断。长度:

/**
 * Prototype Widget: Textarea
 * Automatically resizes a textarea and displays the number of remaining chars
 * 
 * From: http://stackoverflow.com/questions/7477/autosizing-textarea
 * Inspired by: http://github.com/jaz303/jquery-grab-bag/blob/63d7e445b09698272b2923cb081878fd145b5e3d/javascripts/jquery.autogrow-textarea.js
 */
if (window.Widget == undefined) window.Widget = {}; 

Widget.Textarea = Class.create({
  initialize: function(textarea, options){
    this.textarea = $(textarea);
    this.options = $H({
      'min_height' : 30,
      'max_length' : 400
    }).update(options);

    this.textarea.observe('keyup', this.refresh.bind(this));

    this._shadow = new Element('div').setStyle({
      lineHeight : this.textarea.getStyle('lineHeight'),
      fontSize : this.textarea.getStyle('fontSize'),
      fontFamily : this.textarea.getStyle('fontFamily'),
      position : 'absolute',
      top: '-10000px',
      left: '-10000px',
      width: this.textarea.getWidth() + 'px'
    });
    this.textarea.insert({ after: this._shadow });

    this._remainingCharacters = new Element('p').addClassName('remainingCharacters');
    this.textarea.insert({after: this._remainingCharacters});  
    this.refresh();  
  },

  refresh: function(){ 
    this._shadow.update($F(this.textarea).replace(/\n/g, '<br/>'));
    this.textarea.setStyle({
      height: Math.max(parseInt(this._shadow.getHeight()) + parseInt(this.textarea.getStyle('lineHeight').replace('px', '')), this.options.get('min_height')) + 'px'
    });

    // Keep the text/character count inside the limits:
    if($F(this.textarea).length > this.options.get('max_length')){
      text = $F(this.textarea).substring(0, this.options.get('max_length'));
        this.textarea.value = text;
        return false;
    }

    var remaining = this.options.get('max_length') - $F(this.textarea).length;
    this._remainingCharacters.update(Math.abs(remaining)  + ' characters remaining'));
  }
});

答案 15 :(得分:1)

@memical有一个很棒的解决方案,用于使用jQuery在pageload上设置textarea的高度,但对于我的应用程序,我希望能够在用户添加更多内容时增加textarea的高度。我用以下内容构建了memical的解决方案:

$(document).ready(function() {
    var $textarea = $("p.body textarea");
    $textarea.css("height", ($textarea.attr("scrollHeight") + 20));
    $textarea.keyup(function(){
        var current_height = $textarea.css("height").replace("px", "")*1;
        if (current_height + 5 <= $textarea.attr("scrollHeight")) {
            $textarea.css("height", ($textarea.attr("scrollHeight") + 20));
        }
    });
});

它不是很流畅,但它也不是一个面向客户的应用程序,所以平滑性并不重要。 (如果这是面向客户端的,我可能会使用自动调整大小的jQuery插件。)

答案 16 :(得分:1)

使用ASP.NET,只需执行此操作:

<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>Automatic Resize TextBox</title>
        <script type="text/javascript">
            function setHeight(txtarea) {
                txtarea.style.height = txtdesc.scrollHeight + "px";
            }
        </script>
    </head>

    <body>
        <form id="form1" runat="server">
            <asp:TextBox ID="txtarea" runat= "server" TextMode="MultiLine"  onkeyup="setHeight(this);" onkeydown="setHeight(this);" />
        </form>
    </body>
</html>

答案 17 :(得分:1)

对于那些正在编写IE并遇到此问题的人。 IE有一个小技巧,使其成为100%的CSS。

<TEXTAREA style="overflow: visible;" cols="100" ....></TEXTAREA>

你甚至可以为rows =“n”提供一个值,IE会忽略,但其他浏览器会使用。我真的很讨厌实现IE黑客的编码,但这个非常有用。它可能只在Quirks模式下工作。