HTML TextArea自动调整大小

时间:2013-06-24 19:50:29

标签: javascript html css

我希望有一个文本区域,它总是和文本一样大。因此页面可以滚动,文本区域不能滚动 这就是我到现在所做的事情:

<!DOCTYPE html>
<html>
<head>
<style type="text/css">
html, body {height: 100%;}
textarea {
border: none;
width: 100%;
height: 100%;
-webkit-box-sizing: border-box;
line-height: 44px;
font-family:Helvetica;
font-size: 17pt;
-webkit-tap-highlight-color: rgba(0,0,0,0);
background-image:url('linedBack@2x.png');
outline: none;
resize: none;
}
textarea.vert { resize:vertical; }
</style></head><body>
<textarea id="InputTextArea" placeholder="placeholder"></textarea>
</body></html>

5 个答案:

答案 0 :(得分:13)

根据内容行号调整TeaxArea的大小。这是DEMO

JS

function resizeTextarea (id) {
  var a = document.getElementById(id);
  a.style.height = 'auto';
  a.style.height = a.scrollHeight+'px';
}

function init() {
  var a = document.getElementsByTagName('textarea');
  for(var i=0,inb=a.length;i<inb;i++) {
     if(a[i].getAttribute('data-resizable')=='true')
      resizeTextarea(a[i].id);
  }
}

addEventListener('DOMContentLoaded', init);

HTML

<textarea id="InputTextArea" placeholder="placeholder" onkeyup="resizeTextarea('InputTextArea')"></textarea>

答案 1 :(得分:1)

如果您使用的是AngularJS,则可以执行以下操作:

<textarea ng-keyup="ctl.handleTextAreaHeight($event)"></textarea>

在你的控制器中使用它:

this.handleTextAreaHeight = function (e) {
  var element = e.target;

  element.style.overflow = 'hidden';
  element.style.height = 0;
  element.style.height = element.scrollHeight + 'px';
};

答案 2 :(得分:0)

如果有人仍然需要它,那么它的价值就在纯js中。但首先,您可以检查以下内容: Auto expand a textarea using jQuery

    var textAreas = document.getElementsByTagName('textarea');
    try {
        taLength = textAreas.length;
        for (i=0; i < taLength; i++) {
            var taId = textAreas[i].id;
            document.getElementById(taId).addEventListener('input', function(e) {
                e.target.style.height = "auto";
                    //This makes your textarea back to its original size. So you can replace it with any size you want it to have e.g. "120px"
                    //You may need some logic if you have multiple taxtareas with different original sizes
                e.target.style.height = e.target.scrollHeight+'px';
            });
        }
    }
    catch (err) {
        window.alert(err);
    }

我用shubhra的答案来建立那个答案。它很平滑,滚动条也不会出现。

答案 3 :(得分:0)

如果有人需要Vue.js解决方案。这是一个vue指令,用于自动调整文本区域的大小。只需在全局范围内一次注册指令,您就可以将其用于任何文本区域

Vue.directive('resizable', {
    inserted: function (el) {
        el.addEventListener('input', function(e) {
            e.target.style.height = "auto";
            e.target.style.height = e.target.scrollHeight + 'px';
        });
    }
});

html很简单,只需将v-resizable属性放在textarea中

<textarea v-resizable></textarea>

特别感谢AniMir!我正在使用他的输入事件处理程序。

答案 4 :(得分:-1)

使用Bootstrap,它有classess,其中包括classess,根据文本中的文本自动增加文本区域的高度