我有许多不同的查询字段数据,从数据库返回各种高度和长度到多个变量,这些变量映射到网页上自己的文本区域以供显示。我需要一种方法让每个文本区域根据返回的大小自动调整数据。
目前,我为每个文本区域使用一个 javascript 函数(数据自动调整大小),以允许用户在字段大于文本区域时扩展文本:
即
$(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/
在任何更改时将高度设置为 scrollHeight。
由于没有 textarea resize 事件,还要在窗口调整大小时处理它。
关于javascript - 有没有一种方法可以将每个文本区域自动调整为从数据库查询返回的数据的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34662266/