我找到了一个javascript function我想要应用于所有目标元素,在我的情况下,所有textarea都来自页面,但当我将选择器从document.getElementById('text');
更改为document.querySelectorAll('textarea');
或{{ 1}}为了定位所有元素不起作用而且我不明白为什么,我试图将document.getElementsByTagName('textarea')
变量放在text
但仍然不起作用,如果有人可以帮助我的话这个虚假的问题:|
答案 0 :(得分:1)
你在一个循环的正确轨道上,你只是没有走得太远(见评论):
function init () {
var list, i, text;
// Get the list
list = document.getElementsByTagName('textarea');
// Loop through it
for (i = 0; i < list.length; ++i) {
// Get this entry
text = list[i];
// Do things with it
observe(text, 'change', resize);
observe(text, 'cut', delayedResize);
observe(text, 'paste', delayedResize);
observe(text, 'drop', delayedResize);
observe(text, 'keydown', delayedResize);
// Initial `resize` call -- I'm using `.call` in order to
// set `this` to the element during the call, like an event
// does
resize.call(text);
// You'll have to choose *one* of them to focus; I chose the first
if (i == 0) {
text.focus();
text.select();
}
}
function resize () {
// Note that I'm using `this` here, not `text` or `list`
// `this` will refer to the element the event is occurring on
this.style.height = 'auto';
this.style.height = this.scrollHeight+'px';
}
// 0-timeout to get the already changed text
function delayedResize () {
// Again note the use of `this`, also `.bind`.
// `Function#bind` creates a function that, when called,
// calls the original with a specific `this` value
window.setTimeout(resize.bind(this), 0);
}
}