https://jsfiddle.net/ab9hkbL7/1/
let textarea = document.querySelector("#myTextArea");
let tael = textarea.addEventListener.bind(textarea);
let autoResizeTextArea = (e) => {
const element = e.target
element.style.height = 'auto'
element.style.overflowY = 'hidden'
element.style.height = element.scrollHeight + 'px'
}
tael('update', autoResizeTextArea);
tael('keyup', autoResizeTextArea);
//add event listeners for update and keyup
//for demonstration set value big enough that it will resize box:
textarea.value = `lorem Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.`;
//setup promise to resolve after 2 seconds.
//This will simulate fetching external data.
let newPromise = new Promise((res, rej) => {
setTimeout(() => {
res('resolved');
}, 2000)
}).then((success) => {
//create the update event and dispatch it
let myEvent = new CustomEvent("update");
textarea.dispatchEvent(myEvent);
});
的更多信息,请看一看MDN:dispatchEventCustomEvent
以前回答问题https://stackoverflow.com/questions/2490825/how-to-trigger-event-in-javascript – zfrisch
我得到未处理拒绝InvalidStateError :未能在'EventTarget'上执行'dispatchEvent':提供的事件未初始化。我必须添加addEventListener事件吗?我正在添加事件与反应(onKeyUp) – user3882878