我正在尝试在textarea上添加自动调整大小功能。只有输入内容时,下面的代码才有效。但是,如果我只更新来自api的值,则不会触发任何事件。因此,它无法调整大小。 无论如何我可以触发keyup或其他事件触发函数以编程方式获取 scrollHeight 吗?
autoResizeTextArea = (e) => {
const element = e.target
element.style.height = 'auto'
element.style.overflowY = 'hidden'
element.style.height = element.scrollHeight + 'px'
}
答案 0 :(得分:0)
如果你控制改变代码的javascript库,你可以通过调用element.onchange()
<强>更新强>
并且不要忘记将事件监听器onchange
附加到您的元素
请注意,它应该通过js element.onchange
通过html指令设置。
这是一个工作示例jsfiddle
HTML:
<textarea id="mytext"></textarea>
<button id="mybtn">change input</button>
JS:
var onChange = function(){
alert('input changed');
}
var changeInput = function(){
text.value = 'Hello World';
text.onchange();
}
button = document.getElementById('mybtn');
button.onclick = changeInput;
text = document.getElementById('mytext');
text.onchange = onChange;
答案 1 :(得分:0)
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:dispatchEvent CustomEvent