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);
});
ここ
はjsfiddle
HTML実施例であります詳細については、
は、MDNをご覧ください:dispatchEventCustomEvent
は、以前私が未処理の拒絶反応を取得しています質問https://stackoverflow.com/questions/2490825/how-to-trigger-event-in-javascript – zfrisch
に答えInvalidStateError : 'EventTarget'に 'dispatchEvent'を実行できませんでした:提供されたイベントは初期化されていません。 addEventListenerでイベントを追加する必要がありますか?私は現在、反応(onKeyUp)のイベントを追加しています – user3882878