我的前端应用程序需要在其内容更改时自动调整文本区域的高度。我可以通过对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>
因为您是通过代码进行更改的,所以需要使用DOM突变观察器来监视元素的更改。但是,请勿设置value
textarea的,而是value
textarea的为其内容,因此设置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>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句