有没有一种方法可以将每个文本区域自动调整为其大小's从数据库查询返回的数据

Is there a method to autofit each textarea to the size of it's data returned from a database query?

本文关键字:数据 返回 查询 数据库 调整 一种 方法 区域 文本 有没有      更新时间:2023-09-26

我有许多不同的查询字段数据,从数据库向多个变量返回不同的高度和长度,这些变量映射到网页上自己的文本区域以供显示。我需要一种方法让每个文本区域根据返回的大小自动调整数据。

目前,我对每个文本区域使用javascript函数(数据自动resize),以允许用户在字段大于文本区域时扩展文本:

$(document).ready(function () {
    jQuery.each(jQuery('textarea[data-autoresize]'), function () {
        var offset = this.offsetHeight - this.clientHeight;
        var resizeTextarea = function (el) {
            jQuery(el).css('height', 'auto').css('height', el.scrollHeight + offset);
        };
        jQuery(this).on('keyup input', function () {
            resizeTextarea(this);
        }).removeAttr('data-autoresize');
    });
});
<textarea title="If needed, hit ENTER to expand this text area." class="textExpand" readOnly="true" data-autoresize rows="10"> **returnDataFieldVar1** <textarea>

这对于用户在加载数据后手动展开非常有用,并且对于10行的默认文本区域大小来说太大。但为了提高效率和功能,最好让每个文本区域自动适应查询返回的数据,并消除用户必须手动扩展网页上的文本区域的情况。任何关于如何做到这一点的指针或代码示例都将不胜感激!

你在找这样的东西吗?

$(window).on('resize', function(e) {
  $('textarea[data-autoresize]').each(function() {
    var $textarea = $(this);
    $textarea.css('height', 'auto');
    $textarea.css('height', $textarea.prop('scrollHeight') + 'px');
  });
})
$('textarea[data-autoresize]').each(function() {
  $(this).on('keyup input change paste propertychange', function(e) {
    var $textarea = $(this);
    $textarea.css('height', 'auto');
    $textarea.css('height', $textarea.prop('scrollHeight') + 'px');
  });
});

https://jsfiddle.net/ff0xjm4q/

在任何更改时,将高度设置为滚动高度。

由于没有文本区域调整大小事件,因此也可以在窗口调整大小时处理它。