Textarea与文本一起成长

时间:2013-03-26 12:50:52

标签: javascript html css

我正在为商业应用做一些评论功能。 每个评论都是一个跨度,如果你点击它,它会变成一个textarea

问题是我希望textarea占用与其中文本相同的空间(如不编辑时的跨度)

我找到了让行随文本增长的解决方案(jQuery Autosize等),但有没有任何解决方案可以让宽度和高度随文本一起增长?

编辑:在其editmode中,标记看起来像这样(使用Knockout,这就是动态呈现的HTML的样子,实际的KO html是不同的)

<li>
    <span style="display: none">This is a comment</span>
    <textarea>This is a comment</textarea>
    <span class="username">UserOne</span>
    <span class="timestamp">Mars 26 '13</span>
</li>

edit2:所以这是唯一的解决方案: 将cols设置为textarea中的最长行,并将text-area的最大宽度设置为parent-width减去总sibbling宽度?没有使用CSS或jQuery开箱即用的解决方案吗?

2 个答案:

答案 0 :(得分:0)

<style>
div[contenteditable]{
    border: 1px solid black;
    overflow: none;
}
</style>


<div contenteditable>Type me</div>

答案 1 :(得分:0)

您必须在keyup和keydown上动态调整textarea的高度。将高度指定为auto,以便scrollHeight反映所需的高度,然后重新指定高度。请查看以下代码:

        var computedElement = window.getComputedStyle($(element)[0]),
        paddingTop = parseInt(computedElement.paddingTop),
        paddingBottom = parseInt(computedElement.paddingBottom),
        borderBottom = parseInt(computedElement.borderBottom),
        borderTop = parseInt(computedElement.borderTop),
        lineHeight = parseInt(computedElement.lineHeight),
        outerHeight = paddingBottom + paddingTop + borderTop + borderBottom;

        var resize = function() {
          //height:auto resets the height to row=1 to get the scrollHeight without white space
          $(element).css('height', 'auto');
          $(element).height($(element)[0].scrollHeight - outerHeight);
        }

        //first resize to set the existing text
        $timeout(function(){
          if($(element).val().length) {
            resize();
          }
        });

        //resize on keyup and keydown 
        $(element).on('keydown keyup', function() {
          $timeout(function(){
            resize();
          });
        });
相关问题