Textarea 只调整 1 个区域的大小

Textarea only resizes 1 area

我的文本区域有问题。问题是我想要有多个需要在页面加载时调整大小的文本区域。这适用于一个文本区域,但当我插入 2 个文本区域(或更多)时,只有第一个文本区域有效。所以第一个之后的所有文本区域不会调整到它们的高度。

我的代码

<!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>

希望有人能帮助我。

id必须在页面上是唯一的。

如果页面上有多个元素,那么 getElementById 将 return 第一个元素,错误恢复将忽略其他元素。

如果要标识一组元素,则可以使用 class 而不是 id

您可以通过 getElementsByClassNamequerySelectorAll 获取属于 class 成员的元素。这些将 return 一个节点列表,您可以像数组一样循环访问每个元素。

就像@Quentin 所说的“一个 id 在页面上必须是唯一的。

如果页面上有多个元素,getElementById 将 return 第一个,错误恢复将忽略其他元素。"

这是使用 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>