JavaScript 创建自动调整大小的文本区域
在本篇文章中,我们将学习如何在JavaScript中设置自动调整大小的文本区域。此文本区域将能够根据内容自动更改其高度。JavaScript中的自动调整大小文本是一个有用的功能,可以用于编辑多行文本。文本可以根据内部内容自动更改其高度。文本区域的默认行为不允许此功能,但我们可以通过在其上使用输入事件监听器来创建它。
让我们通过一些示例了解如何动态调整文本区域元素的高度:
示例1
在这种情况下,我们将 –
- 使用ID选择文本区域并添加输入事件监听器。
-
当用户调整文本大小时,我们首先将文本高度设置为滚动高度,然后将文本高度设置为自动(默认),最后根据内容调整文本高度。
文件名 – index.html
<html>
<head>
<title>Creating auto-resize text area using JavaScript</title>
<style>
#container {
width: 310px;
}
textarea {
width: 100%;
resize: none;
overflow: hidden;
}
</style>
</head>
<body>
<h3>Auto-resize Text Area</h3>
<div id="container">
<textarea id="myTextArea" rows="1" placeholder="Enter text..."></textarea>
</div>
<script>
const textArea = document.getElementById("myTextArea");
textArea.addEventListener("input", function () {
this.style.height = "auto";
this.style.height = this.scrollHeight + "px";
});
</script>
</body>
</html>
输出
结果将会如下图所示。
示例2
在这个示例中,我们将−
- 定义一个名为resizeTextArea()的函数,该函数在输入事件发生和调整大小事件发生(窗口调整大小)时都会被调用
-
这样做是为了在用户在输入时调整窗口大小时保持文本区域的正确高度
文件名 – index.html
<html>
<head>
<title>Creating auto-resize text area using JavaScript</title>
<style>
#container {
width: 310px;
}
textarea {
width: 100%;
resize: none;
overflow: hidden;
}
</style>
</head>
<body>
<h3>Auto-resize Text Area</h3>
<div id="container">
<textarea id="myTextArea" rows="1" placeholder="Enter text..."></textarea>
</div>
<script>
const textArea = document.getElementById("myTextArea");
function resizeTextArea() {
textArea.style.height = "auto";
textArea.style.height = textArea.scrollHeight + "px";
}
textArea.addEventListener("input", resizeTextArea);
window.addEventListener("resize", resizeTextArea);
</script>
</body>
</html>
输出
结果将类似于下面的图像。
结论
总之,使用JavaScript实现的自动调整大小的文本区域功能为处理多行文本输入和根据其中的内容更改文本区域的高度提供了用户友好的体验。通过使用事件监听器和DOM操作,我们能够创建一个自动调整大小的文本区域。我们了解了使用JavaScript实现自动调整大小的文本区域的概念,并看到了一些解释相同概念的示例。