如何使用JavaScript/jQuery创建自动调整大小的文本区域
文本区域是用于输入的区域,但输入的大小应该很长。我们可以调整输入区域的大小。创建一个文本区域,任务是在我们输入或粘贴内容时自动调整其大小。可以通过使用JavaScript和jQuery来实现。
- 使用JavaScript
- 使用jQuery
方法1:使用JavaScript
为了更改高度,创建一个新函数,用于更改文本区域的style属性。首先将文本区域的高度设置为 auto 。此值使浏览器自动设置元素的高度。这将使文本将滚动,因为文本区域的高度小于文本。紧接着的下一行,将高度再次设置为scrollHeight。
scrollHeight属性 用于以像素为单位返回元素的整个高度,包括padding。这将使文本区域的高度等于整个文本区域的高度,从而有效地调整文本区域以适应文本。
每当输入或文本区域的值发生更改时,都会触发“input”事件。可以使用 addEventListener()方法 来检测此事件。该方法的回调函数设置为上述新建的函数。这将在检测到任何文本输入时触发文本区域重新调整大小,从而根据输入的文本自动调整大小。
示例: 在此示例中,我们将使用JavaScript来调整文本区域的大小。
<!DOCTYPE html>
<html lang="en">
<head>
<title>
How to create auto-resize textarea using JavaScript/jQuery ?
</title>
<style>
#autoresizing {
display: block;
overflow: hidden;
resize: none;
}
</style>
</head>
<body>
<h1 style="color: green">
GeeksforGeeks
</h1>
<b>
Creating a textarea with
auto-resize in JavaScript
</b>
<p>
The textarea below will resize
automatically accounting for
cut, paste and typing text.
</p>
<textarea id="autoresizing">
Try cutting, pasting
or typing here
</textarea>
<script type="text/javascript">
textarea = document.querySelector("#autoresizing");
textarea.addEventListener('input', autoResize, false);
function autoResize() {
this.style.height = 'auto';
this.style.height = this.scrollHeight + 'px';
}
</script>
</body>
</html>
输出:
方法2:使用 jQuery
这与上述方法相似。jQuery中的 on()方法 用于将事件处理程序附加到任何元素上。首先选择textarea元素,然后使用该方法将事件处理程序应用于所选元素。
在回调中声明了一个新函数,该函数更改了textarea的样式属性。首先将textarea的高度设置为’auto’,然后在下一行立即将高度设置为 scrollHeight 。
这将使textarea的高度等于整个文本区域的高度,从而有效调整textarea以适应文本。每当检测到输入的改变时,将执行此函数,textarea将自动调整大小。
示例: 在此示例中,我们将看到 jQuery的使用 。
<!DOCTYPE html>
<html lang="en">
<head>
<title>
How to create auto-resize textarea
using JavaScript/jQuery ?
</title>
<style>
#autoresizing {
display: block;
overflow: hidden;
resize: none;
}
</style>
<script src=
"https://code.jquery.com/jquery-3.4.1.min.js">
</script>
</head>
<body>
<h1 style="color: green">
GeeksforGeeks
</h1>
<b>
Creating a textarea with
auto-resize in JavaScript
</b>
<p>
The textarea below will resize
automatically accounting for cut,
paste and typing text.
</p>
<textarea id="autoresizing">
Try cutting, pasting or typing here
</textarea>
<script type="text/javascript">
$('#autoresizing').on('input', function () {
this.style.height = 'auto';
this.style.height =
(this.scrollHeight) + 'px';
});
</script>
</body>
</html>
输出: