我有以下代码,
function expandTextarea () {
var textareas = document.getElementsByTagName('textarea');
for (var i = 0; i < textareas.length; i++) {
if (textareas[i].scrollHeight > 100) {
textareas[i].style.height = textareas[i].scrollHeight + 2 + 'px';
} else {
textareas[i].style.height = '100px !important';
}
textareas[i].addEventListener('onchange', adjustTextareaHeight(this));
// textareas[i].addEventListener('keyup', adjustTextareaHeight(textareas[i]));
// textareas[i].addEventListener('paste', adjustTextareaHeight(textareas[i]));
// textareas[i].addEventListener('cut', adjustTextareaHeight(textareas[i]));
}
}
function adjustTextareaHeight (textarea) {
console.log(textarea.length);
if (textarea.length > 0) {
textarea.style.height = textarea.scrollHeight + 2 + 'px';
}
}
由于某种原因,事件监听器永远不会被触发。请注意,我的window.onload = function () {}
函数调用了expandTextarea。
当我直接调用expandTextarea时,它运行没有任何问题但是当我进行更改时,按下输入一串,它从不调用onchange事件。
答案 0 :(得分:3)
您必须将功能传递给addEventListener
。目前,您正在传递undefined
,adjustTextareaHeight
的返回值。因此,当事件发生时,浏览器不知道要执行什么。
你想要的是:
textareas[i].addEventListener('change', function() {
adjustTextareaHeight(this);
});
在您的代码中,您立即调用adjustTextareaHeight
(而非更改)。 this
可能是指全局对象(window
),window.length
是undefined
,而不是> 0
。