【问题标题】:HTML Textarea: how to be notified when value changes (input event not triggered)HTML Textarea:如何在值更改时收到通知(未触发输入事件)
【发布时间】:2019-10-04 19:22:57
【问题描述】:

我的前端应用程序需要在其内容更改时自动调整文本区域的高度。我可以通过对input 事件做出反应来部分地使其工作,如下所示:

textarea.addEventListener('input', adjustSize);

问题是在代码中设置值时不会触发这个:

textarea.value = 'some new value';

是否还有一种优雅的方式来捕捉这些变化?我看到的一个选项是手动触发事件,但这对我不起作用,因为我需要对更改做出反应并进行调整大小的上下文显然不知道更改何时发生,以及上下文我进行更改的地方不知道其他一些代码需要知道值何时更改。

var textarea = document.getElementById('myInput');

textarea.addEventListener('input', adjustSize);

// this does not trigger the event handler
setTimeout(write, 1000);

function adjustSize() {
  console.log('adjustSize');
}

function write() {
  textarea.value = 'new textarea value';
}
.myInput {

}
<textarea id="myInput" class="myInput">
  I am textarea
</textarea>

【问题讨论】:

  • 请不要将您的代码发布到第三方网站,因为这些链接会随着时间的推移而失效,从而使您的问题变得毫无意义。相反,将您的可执行代码插入“code sn-p”(创建/编辑问题时在工具栏上可用),就像我为您所做的那样。

标签: javascript html event-handling dom-events


【解决方案1】:

因为您是通过代码进行更改,所以您需要使用DOM Mutation Observer 来监控元素的更改。但是,不要设置textarea的value,而是textarea的value是它的内容,所以设置textContent

var textarea = document.getElementById('myInput');

textarea.addEventListener('input', adjustSize);

setTimeout(write, 1000);

function adjustSize() {
  console.log('adjustSize');
}

function write() {
  // Don't set the value, change the content
  textarea.textContent = 'new textarea value';
}


// Options for the observer (which mutations to observe)
const config = { attributes: true, childList: true, subtree: true };

// Create an observer instance linked to the callback function
const observer = new MutationObserver(adjustSize);

// Start observing the target node for configured mutations
observer.observe(textarea, config);

// Later, you can stop observing
//observer.disconnect();
.myInput {

}
<textarea id="myInput" class="myInput">
  I am textarea
</textarea>

【讨论】:

  • 谢谢。上周我刚和 MutationObserver 一起工作,今天没有想到。干净整洁!
猜你喜欢
  • 2019-12-28
  • 2020-05-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-08
  • 1970-01-01
  • 1970-01-01
  • 2012-08-23
相关资源
最近更新 更多