我的文本区域有问题。问题是我想拥有多个textarea,需要在页面加载时调整其大小。这对于一个textarea来说效果很好,但是当我插入2个textarea(或更多)时,只有第一个可以工作。因此,第一个之后的所有文本区域都不会调整到其高度。
我的代码
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body onload="callOnPageLoad()">
<script>
function callOnPageLoad(){
document.getElementById("textareaEx").style.height="1px";
document.getElementById("textareaEx").style.height=(25+document.getElementById("textareaEx").scrollHeight)+"px";
}
</script>
<textarea onkeyup="callOnPageLoad()" id="textareaEx" style="overflow:hidden">Identify, formulate, research literature, and analyze user needs and taking them into account to solve complex information technology problems, reaching substantiated conclusions using fundamental principles of mathematics, computing fundamentals, technical concepts and practices in the core information technologies, and relevant domain disciplines.</textarea>
</body>
</html>
希望有人可以帮我这个忙。
答案 0 :(得分:3)
id
必须在页面上是唯一的。
如果页面上有多个元素,则getElementById
将返回第一个元素,而错误恢复将忽略其他元素。
如果要标识一组元素,则可以使用class
代替id
。
您可以通过getElementsByClassName
或querySelectorAll
获得属于类成员的元素。这些将返回一个节点列表,您可以像数组一样循环访问该节点列表,依次访问每个元素。
答案 1 :(得分:0)
就像@Quentin一样,“ ID在页面上必须是唯一的。
如果页面上有多个元素,则getElementById将返回第一个元素,而错误恢复将忽略其他元素。”
下面是使用document.getElementsByClassName来迭代/访问所有textArea元素的代码段
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body onload="callOnPageLoad()">
<script>
function callOnPageLoad() {
var ta = document.getElementsByClassName("ta");
for (i = 0; i < ta.length; i++) {
ta[i].style.height = "1px";
ta[i].style.height = (25 + ta[i].scrollHeight) + "px";
}
// document.getElementById("textareaEx").style.height="1px";
// document.getElementById("textareaEx").style.height=(25+document.getElementById("textareaEx").scrollHeight)+"px";
}
</script>
<textarea class="ta" onkeyup="callOnPageLoad()" id="textareaEx" style="overflow:hidden">Identify, formulate, research literature, and analyze user needs and taking them into account to solve complex information technology problems, reaching substantiated conclusions using fundamental principles of mathematics, computing fundamentals, technical concepts and practices in the core information technologies, and relevant domain disciplines.</textarea>
<textarea class="ta" onkeyup="callOnPageLoad()" id="textareaEx1" style="overflow:hidden">Identify, formulate, research literature, and analyze user needs and taking them into account to solve complex information technology problems, reaching substantiated conclusions using fundamental principles of mathematics, computing fundamentals, technical concepts and practices in the core information technologies, and relevant domain disciplines.</textarea>
</body>
</html>