外部修改textarea值无法触发change事件,如何实现高度自适应?
解决textarea值被外部修改后自动调整高度的问题
核心思路
把textarea高度调整的逻辑封装成独立函数,通过MutationObserver监听textarea的value属性变化(替代手动触发事件),当值被外部修改时自动执行高度调整。这种方式不需要依赖手动触发change或input事件,适合框架限制无法主动触发事件的场景。
完整实现代码
HTML 部分
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <textarea name="textarea" id="textarea" class="customTextAreaAuto">a b</textarea> <button onclick="setValue()">Click</button>
JavaScript 部分
// 封装高度调整函数,复用逻辑 function adjustTextareaHeight($textarea) { if ($textarea.outerHeight() > $textarea[0].scrollHeight) { $textarea.height(1); } while ($textarea.outerHeight() < $textarea[0].scrollHeight) { $textarea.height($textarea.height() + 1); } } function setValue() { $('.customTextAreaAuto').val($('.customTextAreaAuto').val() + "aaaaa\n"); } $(function() { // 初始化时调整高度 $('.customTextAreaAuto').each(function() { adjustTextareaHeight($(this)); }).trigger('change'); // 监听手动输入/change事件 $('.customTextAreaAuto').on('input change', function() { adjustTextareaHeight($(this)); }); // 使用MutationObserver监听value属性变化 $('.customTextAreaAuto').each(function() { const target = this; const observer = new MutationObserver(function(mutations) { mutations.forEach(function(mutation) { // 当value属性变化时调整高度 if (mutation.attributeName === 'value') { adjustTextareaHeight($(target)); } }); }); // 配置观察选项:监听属性变化 const config = { attributes: true }; observer.observe(target, config); }); });
兼容旧浏览器的备选方案
如果需要兼容不支持MutationObserver的旧浏览器,可以改用定时器轮询的方式,定期检查textarea的value是否变化,若变化则执行高度调整:
$(function() { $('.customTextAreaAuto').each(function() { const $textarea = $(this); let lastValue = $textarea.val(); setInterval(function() { const currentValue = $textarea.val(); if (currentValue !== lastValue) { lastValue = currentValue; adjustTextareaHeight($textarea); } }, 100); // 轮询间隔可根据需求调整 }); });
内容的提问来源于stack exchange,提问作者N.D.H.Vu
相关产品推荐
相关产品推荐

