如何使用新行调整文本框的大小

How to make textbox resize with new lines

本文关键字:文本 何使用 新行 调整      更新时间:2023-09-26

我在JS中有这段代码,它大部分工作。如果我输入虚拟文本,它会扩展,但是当我按回车键输入新行时,它根本不会扩展。我也从另一个用户那里得到了这个代码,所以我不能为此而受到赞扬。我也不是那么精通JS。

//This span is used to measure the size of the textarea
//it should have the same font and text with the textarea and should be hidden
var span = $('<span>').css('display','inline-block')
                      .css('word-break','break-all')
                      .appendTo('body').css('visibility','hidden');
function initSpan(textarea){
    span.text(textarea.text())
        .width(textarea.width())
        .css('font',textarea.css('font'));
}
$('textarea').on({
    input: function(){
        var text = $(this).val();      
        span.text(text);      
        $(this).height(text ? span.height() : '1.1em');
    },
    focus: function(){           
        initSpan($(this));
    },
});

在 html 中,除了 pre 标记(和适当的 css 规则)之外,每个空格都被替换为单个空格来修复它,只需将 span 替换为 pre 标记:

var pre = $('<pre>').css('display','inline-block')
                    .css('word-break','break-all')
                    .appendTo('body').css('visibility','hidden');
function initPre(textarea){
    pre.text(textarea.text())
        .width(textarea.width())
        .css('font',textarea.css('font'));
}
$('textarea').on({
    input: function(){
        var text = $(this).val();      
        pre.text(text);
        $(this).height(text ? pre.height() : '1.1em');
    },
    focus: function(){           
        initPre($(this));
    },
});

吉斯菲德尔