使用自动调整大小创建textarea

时间:2009-01-17 22:30:42

标签: javascript html resize height textarea

another thread about this,我试过了。但是有一个问题:如果删除内容,textarea不会缩小。我找不到任何方法将其缩小到正确的大小 - clientHeight值会以textarea的完整大小而不是其内容返回。

该页面的代码如下:

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

   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";
   }
}

window.onload = function() {
    document.getElementById("ta").onkeyup = function() {
      FitToContent( this, 500 )
    };
}

46 个答案:

答案 0 :(得分:276)

完全简单的解决方案

更新了 07/05/2019 (改进了对手机和平板电脑的浏览器支持)

以下代码可以使用:

  • 关键输入。
  • 使用粘贴的文字(右击& ctrl + v)。
  • 使用剪切文本(右键单击& ctrl + x)。
  • 预先加载文字。
  • 所有textarea&#39> (多行文本框)网站范围。
  • 使用 Firefox (已测试v31-67)。
  • 使用 Chrome (已测试版本37-74)。
  • 使用 IE (已测试v9-v11)。
  • 使用 Edge (已测试v14-v18)。
  • 使用 IOS Safari
  • 使用 Android浏览器
  • 使用JavaScript 严格模式
  • w3c 验证。
  • 精简高效。

选项1 (使用jQuery)

此选项需要jQuery并且已经过测试,并且正在使用 1.7.2 - 3.3.1

简单 (将此jquery代码添加到主脚本文件中并忘记它。)



$('textarea').each(function () {
  this.setAttribute('style', 'height:' + (this.scrollHeight) + 'px;overflow-y:hidden;');
}).on('input', function () {
  this.style.height = 'auto';
  this.style.height = (this.scrollHeight) + 'px';
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea placeholder="Type, paste, cut text here...">PRELOADED TEXT.
This javascript should now add better support for IOS browsers and Android browsers.</textarea>
<textarea placeholder="Type, paste, cut text here..."></textarea>
&#13;
&#13;
&#13;

Test on jsfiddle


选项2 (纯JavaScript)

简单 (将此JavaScript添加到您的主脚本文件中并忘记它。)

&#13;
&#13;
var tx = document.getElementsByTagName('textarea');
for (var i = 0; i < tx.length; i++) {
  tx[i].setAttribute('style', 'height:' + (tx[i].scrollHeight) + 'px;overflow-y:hidden;');
  tx[i].addEventListener("input", OnInput, false);
}

function OnInput() {
  this.style.height = 'auto';
  this.style.height = (this.scrollHeight) + 'px';
}
&#13;
<textarea placeholder="Type, paste, cut text here...">PRELOADED TEXT. This JavaScript should now add better support for IOS browsers and Android browsers.</textarea>
<textarea placeholder="Type, paste, cut text here..."></textarea>
&#13;
&#13;
&#13;

Test on jsfiddle


选项3 (jQuery扩展)

如果您想要进一步链接到想要自动调整大小的textareas,则非常有用。

jQuery.fn.extend({
  autoHeight: function () {
    function autoHeight_(element) {
      return jQuery(element)
        .css({ 'height': 'auto', 'overflow-y': 'hidden' })
        .height(element.scrollHeight);
    }
    return this.each(function() {
      autoHeight_(this).on('input', function() {
        autoHeight_(this);
      });
    });
  }
});

使用$('textarea').autoHeight()

进行调用

通过JAVASCRIPT更新TEXTAREA

通过JavaScript将内容注入textarea时,请附加以下代码以调用选项1中的函数。

$('textarea').trigger('input');

答案 1 :(得分:195)

这对我有用(Firefox 3.6 / 4.0和Chrome 10/11):

var observe;
if (window.attachEvent) {
    observe = function (element, event, handler) {
        element.attachEvent('on'+event, handler);
    };
}
else {
    observe = function (element, event, handler) {
        element.addEventListener(event, handler, false);
    };
}
function init () {
    var text = document.getElementById('text');
    function resize () {
        text.style.height = 'auto';
        text.style.height = text.scrollHeight+'px';
    }
    /* 0-timeout to get the already changed text */
    function delayedResize () {
        window.setTimeout(resize, 0);
    }
    observe(text, 'change',  resize);
    observe(text, 'cut',     delayedResize);
    observe(text, 'paste',   delayedResize);
    observe(text, 'drop',    delayedResize);
    observe(text, 'keydown', delayedResize);

    text.focus();
    text.select();
    resize();
}
textarea {
    border: 0 none white;
    overflow: hidden;
    padding: 0;
    outline: none;
    background-color: #D0D0D0;
}
<body onload="init();">
<textarea rows="1" style="height:1em;" id="text"></textarea>
</body>

如果您想在jsfiddle 上试用 它从一行开始,只增长所需的确切数量。单个textarea是可以的,但是我想写一些内容,我会有许多这样的textarea s(大约一个通常在大文本文档中有行)。在那种情况下,它真的很慢。 (在Firefox中,它非常慢。)所以我真的想要一种使用纯CSS的方法。 contenteditable可以实现这一点,但我希望它只是纯文本。

答案 2 :(得分:62)

jQuery解决方案 调整css以符合您的要求

...的CSS

div#container textarea {
    min-width: 270px;
    width: 270px;
    height: 22px;
    line-height: 24px;
    min-height: 22px;
    overflow-y: hidden; /* fixes scrollbar flash - kudos to @brettjonesdev */
    padding-top: 1.1em; /* fixes text jump on Enter keypress */
}

...的JavaScript

// auto adjust the height of
$('#container').delegate( 'textarea', 'keydown', function (){
    $(this).height( 0 );
    $(this).height( this.scrollHeight );
});
$('#container').find( 'textarea' ).keydown();

或者替代jQuery 1.7 + ...

// auto adjust the height of
$('#container').on( 'keyup', 'textarea', function (){
    $(this).height( 0 );
    $(this).height( this.scrollHeight );
});
$('#container').find( 'textarea' ).keyup();

我创造了一个小提琴,绝对最小的造型作为实验的起点...... http://jsfiddle.net/53eAy/951/

答案 3 :(得分:28)

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Textarea autoresize</title>
    <style>
    textarea {
        overflow: hidden;
    }
    </style>
    <script>
    function resizeTextarea(ev) {
        this.style.height = '24px';
        this.style.height = this.scrollHeight + 12 + 'px';
    }

    var te = document.querySelector('textarea');
    te.addEventListener('input', resizeTextarea);
    </script>
</head>
<body>
    <textarea></textarea>
</body>
</html>

在Firefox 14和Chromium 18中测试过。数字24和12是任意的,测试看看哪种最适合你。

你可以没有样式和脚本标签,但它变得有点凌乱imho(这是旧式HTML + JS,不鼓励)。

<textarea style="overflow: hidden" onkeyup="this.style.height='24px'; this.style.height = this.scrollHeight + 12 + 'px';"></textarea>

编辑:现代化的代码。将onkeyup属性更改为addEventListener 编辑:keydown比keyup更好 编辑:使用前声明功能
编辑:输入比keydown更好(thnx @ WASD42&amp; @ MA-Maddin)

jsfiddle

答案 4 :(得分:24)

对我来说,最好的解决方案(有效且简短)是:

    $(document).on('input', 'textarea', function () {
        $(this).outerHeight(38).outerHeight(this.scrollHeight); // 38 or '1em' -min-height
    }); 

它就像一个没有任何眨眼的魅力(也带有鼠标),切割,进入并缩小到合适的尺寸。

请查看jsFiddle

答案 5 :(得分:16)

您正在使用当前clientHeight和内容scrollHeight的较高值。通过删除内容使scrollHeight变小时,计算出的区域不能变小,因为之前由style.height设置的clientHeight将其保持打开状态。您可以使用max()scrollHeight和您从textarea.rows预定义或计算的最小高度值。

通常,您可能不应该真正依赖于表单控件上的scrollHeight。除了传统上不受广泛支持的scrollHeight之外,HTML / CSS没有说明内部如何实现表单控件,并且不保证scrollHeight将是有意义的。 (传统上一些浏览器已经使用操作系统小部件来完成任务,因此无法在内部进行CSS和DOM交互。)在尝试启用效果之前,至少要嗅探scrollHeight / clientHeight的存在。

另一种可能的替代方法是避免问题,如果它更广泛地工作是重要的可能是使用大小与textarea相同宽度的隐藏div,并设置相同的字体。在keyup上,你将文本从textarea复制到隐藏div中的文本节点(记住用换行符替换'\ n',如果你使用innerHTML,则正确地转义'&lt;'/'&amp;')。然后简单地测量div的offsetHeight将为您提供所需的高度。

答案 6 :(得分:14)

如果您不需要支持IE8,可以使用input事件:

var resizingTextareas = [].slice.call(document.querySelectorAll('textarea[autoresize]'));

resizingTextareas.forEach(function(textarea) {
  textarea.addEventListener('input', autoresize, false);
});

function autoresize() {
  this.style.height = 'auto';
  this.style.height = this.scrollHeight+'px';
  this.scrollTop = this.scrollHeight;
  window.scrollTo(window.scrollLeft,(this.scrollTop+this.scrollHeight));
}

现在你只需要添加一些CSS就可以了:

textarea[autoresize] {
  display: block;
  overflow: hidden;
  resize: none;
}

<强>用法:

<textarea autoresize>Type here and I’ll resize.</textarea>

您可以详细了解其工作原理 on my blog post

答案 7 :(得分:11)

<强>自动调整大小

https://github.com/jackmoore/autosize

正常工作,独立,流行(截至2018年10月的3.0k + GitHub星),cdnjs}和轻量级(~3.5k)。演示:

&#13;
&#13;
<textarea id="autosize" style="width:200px;">a
J   b
c</textarea>
<script src="https://cdnjs.cloudflare.com/ajax/libs/autosize.js/4.0.2/autosize.min.js"></script>
<script>autosize(document.querySelectorAll('#autosize'));</script>
&#13;
&#13;
&#13;

BTW,如果您使用的是ACE编辑器,请使用maxLines: InfinityAutomatically adjust height to contents in Ace Cloud 9 editor

答案 8 :(得分:6)

有没有人认为满足?没有乱七八糟的滚动,而且我喜欢它的唯一JS就是你打算在模糊上保存数据......显然,它在所有流行的浏览器上兼容:http://caniuse.com/#feat=contenteditable < / p>

只需将其设置为文本框样式,然后自动调整...使其最小高度成为首选文本高度并具有此值。

这种方法很酷,你可以在某些浏览器上保存和标记。

http://jsfiddle.net/gbutiri/v31o8xfo/

<style>
.autoheight {
    min-height: 16px;
    font-size: 16px;
    margin: 0;
    padding: 10px;
    font-family: Arial;
    line-height: 16px;
    box-sizing: border-box;
    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
    overflow: hidden;
    resize: none;
    border: 1px solid #ccc;
    outline: none;
    width: 200px;
}
</style>
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script>
$(document).on('blur','.autoheight',function(e) {
    var $this = $(this);
    // The text is here. Do whatever you want with it.
    console.log($this.html());
});

</script>
<div class="autoheight contenteditable" contenteditable="true">Mickey Mouse</div>

答案 9 :(得分:4)

作为一种不同的方法,您可以使用<span>自动调整其大小。您需要通过添加contenteditable="true"属性使其可编辑,并且您已完成:

div {
  width: 200px;
}

span {
  border: 1px solid #000;
  padding: 5px;
}
<div>
  <span contenteditable="true">This text can be edited by the user</span>
</div>

这种方法的唯一问题是,如果要将值作为表单的一部分提交,则必须由JavaScript自己完成。这样做相对容易。例如,您可以添加隐藏字段,并在表单的onsubmit事件中将span的值分配给隐藏字段,然后该字段将随表单自动提交。

答案 10 :(得分:4)

以下适用于剪切,粘贴等,无论这些操作是来自鼠标,键盘快捷键,从菜单栏中选择一个选项......几个答案采取类似的方法,但他们不考虑对于盒子大小调整,这就是他们错误地应用样式overflow: hidden

的原因

我执行以下操作,这对于max-heightrows最适合最小和最大身高也很有效。

function adjust() {
  var style = this.currentStyle || window.getComputedStyle(this);
  var boxSizing = style.boxSizing === 'border-box'
      ? parseInt(style.borderBottomWidth, 10) +
        parseInt(style.borderTopWidth, 10)
      : 0;
  this.style.height = '';
  this.style.height = (this.scrollHeight + boxSizing) + 'px';
};

var textarea = document.getElementById("ta");
if ('onpropertychange' in textarea) { // IE
  textarea.onpropertychange = adjust;
} else if ('oninput' in textarea) {
  textarea.oninput = adjust;
}
setTimeout(adjust.bind(textarea));
textarea {
  resize: none;
  max-height: 150px;
  border: 1px solid #999;
  outline: none;
  font: 18px sans-serif;
  color: #333;
  width: 100%;
  padding: 8px 14px;
  box-sizing: border-box;
}
<textarea rows="3" id="ta">
Try adding several lines to this.
</textarea>

为了绝对完整,您应该在几种情况下调用adjust函数:

  1. 窗口调整大小事件,如果textarea的宽度随窗口大小调整而改变,或其他更改textarea宽度的事件
  2. textarea的{​​{1}}样式属性发生变化时,例如当它从display(隐藏)转移到none
  3. 以编程方式更改block的值时
  4. 请注意,使用textarea或获取window.getComputedStyle可能会在某种程度上计算成本,因此您可能希望缓存结果。

    适用于IE6,所以我真的希望得到足够的支持。

答案 11 :(得分:4)

方法略有不同。

<div style="position: relative">
  <pre style="white-space: pre-wrap; word-wrap: break-word"></pre>
  <textarea style="position: absolute; top: 0; left: 0; width: 100%; height: 100%"></textarea>
</div>

我们的想法是将文本从textarea复制到pre,让CSS确保它们的大小相同。

好处是框架提供了简单的工具来移动文本而不触及任何事件。也就是说,在AngularJS中,您可以向ng-model="foo" ng-trim="false"添加textarea,向ng-bind="foo + '\n'"添加pre。请参阅fiddle

请确保pre的字体大小与textarea相同。

答案 12 :(得分:4)

我将以下代码用于多个textareas。在Chrome 12,Firefox 5和IE 9中正常工作,即使在textareas中执行了删除,剪切和粘贴操作。

<!-- language: lang-html -->
<style type='text/css'>
textarea { border:0 none; overflow:hidden; outline:none; background-color:#eee }
</style>
<textarea style='height:100px;font-family:arial' id="txt1"></textarea>
<textarea style='height:125px;font-family:arial' id="txt2"></textarea>
<textarea style='height:150px;font-family:arial' id="txt3"></textarea>
<textarea style='height:175px;font-family:arial' id="txt4"></textarea>
<script type='text/javascript'>
function attachAutoResizeEvents()
{   for(i=1;i<=4;i++)
    {   var txtX=document.getElementById('txt'+i)
        var minH=txtX.style.height.substr(0,txtX.style.height.indexOf('px'))
        txtX.onchange=new Function("resize(this,"+minH+")")
        txtX.onkeyup=new Function("resize(this,"+minH+")")
        txtX.onchange(txtX,minH)
    }
}
function resize(txtX,minH)
{   txtX.style.height = 'auto' // required when delete, cut or paste is performed
    txtX.style.height = txtX.scrollHeight+'px'
    if(txtX.scrollHeight<=minH)
        txtX.style.height = minH+'px'
}
window.onload=attachAutoResizeEvents
</script>

答案 13 :(得分:2)

您可以在键入以下内容时使用JQuery展开textarea

$(document).find('textarea').each(function () {
  var offset = this.offsetHeight - this.clientHeight;

  $(this).on('keyup input focus', function () {
    $(this).css('height', 'auto').css('height', this.scrollHeight + offset);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div>
<textarea name="note"></textarea>
<div>

答案 14 :(得分:2)

我知道用jquery实现这个的简短而正确的方法。不需要额外的隐藏div并且可以在大多数浏览器中使用

<script type="text/javascript">$(function(){
$("textarea").live("keyup keydown",function(){
var h=$(this);
h.height(60).height(h[0].scrollHeight);//where 60 is minimum height of textarea
});});

</script>

答案 15 :(得分:2)

这是panzi的答案的angularjs指令。

 module.directive('autoHeight', function() {
        return {
            restrict: 'A',
            link: function(scope, element, attrs) {
                element = element[0];
                var resize = function(){
                    element.style.height = 'auto';
                    element.style.height = (element.scrollHeight)+'px';
                };
                element.addEventListener('change', resize, false);
                element.addEventListener('cut',    resize, false);
                element.addEventListener('paste',  resize, false);
                element.addEventListener('drop',   resize, false);
                element.addEventListener('keydown',resize, false);

                setTimeout(resize, 100);
            }
        };
    });

HTML:

<textarea ng-model="foo" auto-height></textarea>

答案 16 :(得分:2)

有点修正。在Opera中完美运行

  $('textarea').bind('keyup keypress', function() {
      $(this).height('');
      var brCount = this.value.split('\n').length;
      this.rows = brCount+1; //++ To remove twitching
      var areaH = this.scrollHeight,
          lineHeight = $(this).css('line-height').replace('px',''),
          calcRows = Math.floor(areaH/lineHeight);
      this.rows = calcRows;
  });

答案 17 :(得分:2)

我不知道是否有人提到这种方式,但在某些情况下,可以使用行属性

来调整高度
textarea.setAttribute('rows',breaks);

Demo

答案 18 :(得分:1)

可接受的答案很好。但这是用于此简单功能的大量代码。下面的代码可以解决问题。

   $(document).on("keypress", "textarea", function (e) {
    var height = $(this).css("height");
    var iScrollHeight = $(this).prop("scrollHeight");
    $(this).css('height',iScrollHeight);
    });

答案 19 :(得分:1)

想要在新版本的Angular中实现相同目标的人。

Grab textArea elementRef。

@ViewChild('textArea', { read: ElementRef }) textArea: ElementRef;

public autoShrinkGrow() {
    textArea.style.overflow = 'hidden';
    textArea.style.height = '0px';
    textArea.style.height = textArea.scrollHeight + 'px';
}

<textarea (keyup)="autoGrow()" #textArea></textarea>

我还添加了另一个用例,当某些用户希望将文本区域的高度增加到一定高度,然后在其上加上overflow:scroll时,可能会方便一些阅读线程的用户,上述方法可以扩展实现上述用例。

  public autoGrowShrinkToCertainHeight() {
    const textArea = this.textArea.nativeElement;
    if (textArea.scrollHeight > 77) {
      textArea.style.overflow = 'auto';
      return;
    }
    else {
      textArea.style.overflow = 'hidden';
      textArea.style.height = '0px';
      textArea.style.height = textArea.scrollHeight + 'px';
    }
  }

答案 20 :(得分:1)

我的实现非常简单,计算输入中的行数(最少2行以表明它是一个文本区域):

textarea.rows = Math.max(2, textarea.value.split("\n").length) // # oninput

完整的激励示例:https://jsbin.com/kajosolini/1/edit?html,js,output

(这与浏览器的手动调整大小手柄配合使用)

答案 21 :(得分:1)

只需使用<pre> </pre>等一些样式:

    pre {
        font-family: Arial, Helvetica, sans-serif;
        white-space: pre-wrap;
        word-wrap: break-word;
        font-size: 12px;
        line-height: 16px;
    }

答案 22 :(得分:1)

here

找到了一个班轮
<textarea name="text" oninput='this.style.height = "";this.style.height = this.scrollHeight + "px"'></textarea>

答案 23 :(得分:1)

此代码适用于粘贴和选择删除。

onKeyPressTextMessage = function(){
			var textArea = event.currentTarget;
    	textArea.style.height = 'auto';
    	textArea.style.height = textArea.scrollHeight + 'px';
};
<textarea onkeyup="onKeyPressTextMessage(event)" name="welcomeContentTmpl" id="welcomeContent" onblur="onblurWelcomeTitle(event)" rows="2" cols="40" maxlength="320"></textarea>

以下是JSFiddle

答案 24 :(得分:1)

这是一个更简单,更清洁的方法:

// adjust height of textarea.auto-height
$(document).on( 'keyup', 'textarea.auto-height', function (e){
    $(this).css('height', 'auto' ); // you can have this here or declared in CSS instead
    $(this).height( this.scrollHeight );
}).keyup();

//和CSS

textarea.auto-height {
    resize: vertical;
    max-height: 600px; /* set as you need it */
    height: auto;      /* can be set here of in JS */
    overflow-y: auto;
    word-wrap:break-word
}

所需要的只是将.auto-height课程添加到您要定位的任何textarea

在FF,Chrome和Safari中测试过。如果出于任何原因,这对您不起作用,请告诉我。但是,这是我发现这个最干净,最简单的方法。而且效果很棒! :d

答案 25 :(得分:1)

这里的一些答案不考虑填充。

假设你有一个maxHeight,你不想过去,这对我有用:

    // obviously requires jQuery

    // element is the textarea DOM node

    var $el = $(element);
    // inner height is height + padding
    // outerHeight includes border (and possibly margins too?)
    var padding = $el.innerHeight() - $el.height();
    var originalHeight = $el.height();

    // XXX: Don't leave this hardcoded
    var maxHeight = 300;

    var adjust = function() {
        // reset it to the original height so that scrollHeight makes sense
        $el.height(originalHeight);

        // this is the desired height (adjusted to content size)
        var height = element.scrollHeight - padding;

        // If you don't want a maxHeight, you can ignore this
        height = Math.min(height, maxHeight);

        // Set the height to the new adjusted height
        $el.height(height);
    }

    // The input event only works on modern browsers
    element.addEventListener('input', adjust);

答案 26 :(得分:0)

对于那些希望textarea在宽度和高度上自动调整大小的人:

HTML:

<textarea class='textbox'></textarea>
<div>
  <span class='tmp_textbox'></span>
</div>

CSS:

.textbox,
.tmp_textbox {
  font-family: 'Arial';
  font-size: 12px;
  resize: none;
  overflow:hidden;
}

.tmp_textbox {
  display: none;
}

jQuery的:

$(function(){
  //alert($('.textbox').css('padding'))
  $('.textbox').on('keyup change', checkSize)
  $('.textbox').trigger('keyup')

  function checkSize(){
    var str = $(this).val().replace(/\r?\n/g, '<br/>');
    $('.tmp_textbox').html( str )
    console.log($(this).val())

    var strArr = str.split('<br/>')
    var row = strArr.length
    $('.textbox').attr('rows', row)
    $('.textbox').width( $('.tmp_textbox').width() + parseInt($('.textbox').css('padding')) * 2 + 10 )
  }
})

<强> Codepen:

http://codepen.io/anon/pen/yNpvJJ

干杯,

答案 27 :(得分:0)

这是一种基于行的方法,可让您为 textarea 设置最大行数,之后 textarea 将显示滚动条。除了以 rows 属性的形式调整其高度外,这还会在键入或执行剪切和粘贴等操作时自动扩展其宽度。

如果 textarea 除了占位符之外没有任何内容,它将根据占位符文本调整其宽度和高度。

这个版本的一个缺点是它会根据文本宽度无限增加其宽度。因此,您需要为 max-width 设置一个 textarea 值。一个简单的 max-width: 100%; 也可以解决问题。此宽度扩展功能主要基于 inputtype="text" 字段。您可以在此answer中阅读更多相关信息。

const textarea = document.querySelector('textarea');

setTextareaWidthHeight(textarea);
textarea.addEventListener('input', setTextareaWidthHeight.bind(this, textarea));

function getInputWidth(element) {
    const text = element.value || element.placeholder;
    const elementStyle = window.getComputedStyle(element);
    const fontProperty = elementStyle.font;
    const horizontalBorder = parseFloat(elementStyle.borderLeftWidth) + parseFloat(elementStyle.borderRightWidth);
    const horizontalPadding = parseFloat(elementStyle.paddingLeft) + parseFloat(elementStyle.paddingRight);

    const canvas = document.createElement('canvas');
    const context = canvas.getContext('2d');
    context.font = fontProperty;
    const textWidth = context.measureText(text).width;

    const totalWidth = horizontalBorder + horizontalPadding + textWidth + "px";
    return totalWidth;
}

function setTextareaWidthHeight(element) {
    // store minimum and maximum rows attribute value that should be imposed
    const minRows = 1;
    const maxRows = 5;

    // store initial inline overflow property value in a variable for later reverting to original condition
    const initialInlineOverflowY = element.style.overflowY;

    // change overflow-y property value to hidden to overcome inconsistent width differences caused by any scrollbar width
    element.style.overflowY = 'hidden';

    const totalWidth = getInputWidth(element);
    element.style.width = totalWidth;

    let rows = minRows;
    element.setAttribute("rows", rows);

    while (rows <= maxRows && element.scrollHeight !== element.clientHeight) {
        element.setAttribute("rows", rows);
        rows++;
    }

    // change overflow to its original condition
    if (initialInlineOverflowY) {
        element.style.overflowY = initialInlineOverflowY;
    } else {
        element.style.removeProperty("overflow-y");
    }
}
textarea {
    max-width: 100%;
}
<textarea placeholder="Lorem ipsum dolor sit amet"></textarea>

答案 28 :(得分:0)

我创建了a small (7kb) custom element,可以为您处理所有这些大小调整逻辑。

它在任何地方都可以使用,因为它是作为自定义元素实现的。其中包括:虚拟DOM(React,Elm等),服务器端渲染的东西(如PHP)和纯朴的HTML文件。

除了侦听输入事件外,它还具有一个计时器,该计时器每100毫秒触发一次,以确保在文本内容通过其他某种方式更改的情况下一切仍然正常。

这是它的工作方式:

// At the top of one of your Javascript files
import "autoheight-textarea";

或包含为脚本标签

<script src="//cdn.jsdelivr.net/npm/autoheight-textarea@1.0.1/dist/main.min.js"></script>

然后像这样包装您的textarea元素

HTML文件

<autoheight-textarea>
  <textarea rows="4" placeholder="Type something"></textarea>
<autoheight-textarea>

React.js组件

const MyComponent = () => {
  return (
    <autoheight-textarea>
      <textarea rows={4} placeholder="Type something..." />
    </autoheight-textarea>
  );
}

这是Codesandbox上的基本演示:https://codesandbox.io/s/unruffled-http-2vm4c

您可以在这里获取软件包:https://www.npmjs.com/package/autoheight-textarea

如果您只是想知道调整大小的逻辑,可以看看以下功能:https://github.com/Ahrengot/autoheight-textarea/blob/master/src/index.ts#L74-L85

答案 29 :(得分:0)

对于Angular 2+,只需执行此操作

<textarea (keydown)="resize($event)"></textarea>


resize(e) {
    setTimeout(() => {
      e.target.style.height = 'auto';
      e.target.style.height = (e.target.scrollHeight)+'px';
    }, 0);
  }

textarea {
  resize: none;
  overflow: hidden;
}

答案 30 :(得分:0)

我知道我迟到了这个聚会,但是我遇到的最简单的解决方案是将您的文本区域内容拆分为换行符,并更新textarea元素的行。

<textarea id="my-text-area"></textarea>

<script>
  $(function() {
    const txtArea = $('#my-text-area')
    const val = txtArea.val()
    const rowLength = val.split('\n')
    txtArea.attr('rows', rowLength)
  })
</script>

答案 31 :(得分:0)

我发现的最好方式:

$("textarea.auto-grow").each( function(){
    $(this).keyup(function(){
        $(this).height( $(this)[0].scrollHeight - Number( $(this).css("font-size").replace("px", "") ) );
    });
});

其他方式都有字体大小错误。

这就是为什么这是最好的。

答案 32 :(得分:0)

使用qQuery的MakeTextAreaResisable

function MakeTextAreaResisable(id) {
    var o = $(id);
    o.css("overflow-y", "hidden");

    function ResizeTextArea() {
        o.height('auto');
        o.height(o[0].scrollHeight);
    }

    o.on('change', function (e) {
        ResizeTextArea();
    });

    o.on('cut paste drop keydown', function (e) {
        window.setTimeout(ResizeTextArea, 0);
    });

    o.focus();
    o.select();
    ResizeTextArea();
}

答案 33 :(得分:0)

没有一个答案似乎有效。但这个对我有用: https://coderwall.com/p/imkqoq/resize-textarea-to-fit-content

$('#content').on( 'change keyup keydown paste cut', 'textarea', function (){
    $(this).height(0).height(this.scrollHeight);
}).find( 'textarea' ).change();

答案 34 :(得分:0)

这是我在为TextArea使用MVC HTML Helper时所做的。我有很多textarea元素,所以必须使用Model Id区分它们。

 @Html.TextAreaFor(m => m.Text, 2, 1, new { id = "text" + Model.Id, onkeyup = "resizeTextBox(" + Model.Id + ");" })

并在脚本中添加了这个:

   function resizeTextBox(ID) {            
        var text = document.getElementById('text' + ID);
        text.style.height = 'auto';
        text.style.height = text.scrollHeight + 'px';            
    }

我在IE10和Firefox23上测试了它

答案 35 :(得分:0)

原生Javascript解决方案在Firefox中没有闪烁,比withclientHeight方法更快......

1)将div.textarea选择器添加到包含textarea的所有选择器中。不要忘记添加box-sizing: border-box;

2)包括这个脚本:

function resizeAll()
{
   var textarea=document.querySelectorAll('textarea');
   for(var i=textarea.length-1; i>=0; i--)
      resize(textarea[i]);
}

function resize(textarea)
{
   var div = document.createElement("div");
   div.setAttribute("class","textarea");
   div.innerText=textarea.value+"\r\n";
   div.setAttribute("style","width:"+textarea.offsetWidth+'px;display:block;height:auto;left:0px;top:0px;position:fixed;z-index:-200;visibility:hidden;word-wrap:break-word;overflow:hidden;');
   textarea.form.appendChild(div);
   var h=div.offsetHeight;
   div.parentNode.removeChild(div);
   textarea.style.height=h+'px';
}

function resizeOnInput(e)
{
   var textarea=document.querySelectorAll('textarea');
   for(var i=textarea.length-1; i>=0; i--)
      textarea[i].addEventListener("input",function(e){resize(e.target); return false;},false);
}

window.addEventListener("resize",function(){resizeAll();}, false);
window.addEventListener("load",function(){resizeAll();}, false);
resizeOnInput();

在IE11,Firefox和Chrome上测试过。

此解决方案创建类似于textarea的div,包括内部文本和度量高度。

答案 36 :(得分:0)

您可以使用此代码:

<强> Coffescript:

jQuery.fn.extend autoHeightTextarea: ->
  autoHeightTextarea_ = (element) ->
    jQuery(element).css(
      'height': 'auto'
      'overflow-y': 'hidden').height element.scrollHeight

  @each ->
    autoHeightTextarea_(@).on 'input', ->
      autoHeightTextarea_ @

$('textarea_class_or_id`').autoHeightTextarea()

<强>的Javascript

jQuery.fn.extend({
  autoHeightTextarea: function() {
    var autoHeightTextarea_;
    autoHeightTextarea_ = function(element) {
      return jQuery(element).css({
        'height': 'auto',
        'overflow-y': 'hidden'
      }).height(element.scrollHeight);
    };
    return this.each(function() {
      return autoHeightTextarea_(this).on('input', function() {
        return autoHeightTextarea_(this);
      });
    });
  }
});

$('textarea_class_or_id`').autoHeightTextarea();

答案 37 :(得分:0)

您可以使用这段代码来计算textarea所需的行数:

plone.app.contenttypes

textarea.rows = 1; if (textarea.scrollHeight > textarea.clientHeight) textarea.rows = textarea.scrollHeight / textarea.clientHeight; input事件上对其进行计算,以获得自动调整大小的效果。 Angular中的示例:

模板代码:

window:resize

自动wrap.directive.ts

<textarea rows="1" reAutoWrap></textarea>

答案 38 :(得分:0)

这是Moussawi7answer的jQuery版本。

$(function() {
  $("textarea.auto-grow").on("input", function() {
    var element = $(this)[0];
    element.style.height = "5px";
    element.style.height = (element.scrollHeight) + "px";
  });
})
textarea {
  resize: none;
  overflow: auto;
  width: 100%;
  min-height: 50px;
  max-height: 150px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea class="auto-grow"></textarea>

答案 39 :(得分:0)

jQuery解决方案是将textarea的高度设置为&#39; auto&#39;,检查scrollHeight,然后每次textarea更改时调整textarea的高度(JSFiddle) :

$('textarea').on( 'input', function(){
    $(this).height( 'auto' ).height( this.scrollHeight );
});

如果你动态添加textareas(通过AJAX或其他),你可以在$(document).ready中添加它,以确保所有textareas与class&#39; autoheight&#39;保持与其内容相同的高度:

$(document).on( 'input', 'textarea.autoheight', function() {
    $(this).height( 'auto' ).height( this.scrollHeight );
});

在Chrome,Firefox,Opera和IE中测试并使用。还支持剪切和粘贴,长词等。

答案 40 :(得分:-1)

React 的示例实现:

const {
  useLayoutEffect,
  useState,
  useRef
} = React;

const TextArea = () => {
  const ref = useRef();
  const [value, setValue] = useState('Some initial text that both wraps and uses\nnew\nlines');

  // This only tracks the auto-sized height so we can tell if the user has manually resized
  const autoHeight = useRef();

  useLayoutEffect(() => {
    if (!ref.current) {
      return;
    }

    if (
      autoHeight.current !== undefined &&
      ref.current.style.height !== autoHeight.current
    ) {
      // don't auto size if the user has manually changed the height
      return;
    }

    ref.current.style.height = "auto";
    ref.current.style.overflow = "hidden";
    const next = `${ref.current.scrollHeight}px`;
    ref.current.style.height = next;
    autoHeight.current = next;
    ref.current.style.overflow = "auto";
  }, [value, ref, autoHeight]);


  return (
    <textarea
      ref={ref}
      style={{
        resize: 'vertical',
        minHeight: '1em',
      }}
      value={value}
      onChange={event => setValue(event.target.value)}
    />
  );
}

ReactDOM.render(<TextArea />, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="app"></div>

答案 41 :(得分:-1)

我推荐来自http://javierjulio.github.io/textarea-autosize的javascript库。

根据评论,在插件使用上添加示例代码块:

<textarea class="js-auto-size" rows="1"></textarea>

<script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
<script src="jquery.textarea_autosize.min.js"></script>
<script>
$('textarea.js-auto-size').textareaAutoSize();
</script>

所需的最低CSS:

textarea {
  box-sizing: border-box;
  max-height: 160px; // optional but recommended
  min-height: 38px;
  overflow-x: hidden; // for Firefox (issue #5)
}

答案 42 :(得分:-1)

我可以使用以下jQuery函数在IE9和Chrome中设置TextArea大小。它绑定到$(document).ready()函数中定义的选择器中的textarea对象。

function autoResize(obj, size) {
    obj.keyup(function () {
        if ($(this).val().length > size-1) {
            $(this).val( function() {
                $(this).height(function() {
                    return this.scrollHeight + 13;
                });
                alert('The maximum comment length is '+size+' characters.');
                return $(this).val().substring(0, size-1);
            });
        }
        $(this).height(function() {
            if  ($(this).val() == '') {
                return 15;
            } else {
                $(this).height(15);
                return ($(this).attr('scrollHeight')-2);
            }
        });
    }).keyup();
}

在我的$(document).ready()函数中,我对此页面上的所有textarea调用都进行了以下调用。

$('textarea').each( function() {
        autoResize($(this), 250);
});

250是我文字区域的字符数限制。这将增长到文本大小允许的大小(根据您的字符数和字体大小)。当您从textarea中删除字符或者用户最初粘贴太多文本时,它还会适当缩小文本区域。

答案 43 :(得分:-1)

$('textarea').bind('keyup change', function() {
    var $this = $(this), $offset = this.offsetHeight;
    $offset > $this.height() && $offset < 300 ?
        $this.css('height ', $offset)
            .attr('rows', $this.val().split('\n').length)
            .css({'height' : $this.attr('scrollHeight'),'overflow' : 'hidden'}) :
        $this.css('overflow','auto');
});

答案 44 :(得分:-1)

我在常见浏览器中测试过脚本,但在Chrome和Safari中失败了。这是因为不断更新的scrollHeight变量。

我已经使用jQuery应用了DisgruntledGoat脚本并添加了chrome fix

function fitToContent(/* JQuery */text, /* Number */maxHeight) {
    var adjustedHeight = text.height();
    var relative_error = parseInt(text.attr('relative_error'));
    if (!maxHeight || maxHeight > adjustedHeight) {
        adjustedHeight = Math.max(text[0].scrollHeight, adjustedHeight);
        if (maxHeight)
            adjustedHeight = Math.min(maxHeight, adjustedHeight);
        if ((adjustedHeight - relative_error) > text.height()) {
            text.css('height', (adjustedHeight - relative_error) + "px");
            // chrome fix
            if (text[0].scrollHeight != adjustedHeight) {
                var relative = text[0].scrollHeight - adjustedHeight;
                if (relative_error != relative) {
                    text.attr('relative_error', relative + relative_error);
                }
            }
        }
    }
}

function autoResizeText(/* Number */maxHeight) {
    var resize = function() {
        fitToContent($(this), maxHeight);
    };
    $("textarea").attr('relative_error', 0);
    $("textarea").each(resize);
    $("textarea").keyup(resize).keydown(resize);
}

答案 45 :(得分:-2)

如果可以信任scrollHeight,那么:

textarea.onkeyup=function() {
  this.style.height='';
  this.rows=this.value.split('\n').length;
  this.style.height=this.scrollHeight+'px';
}
相关问题