jquery - 如何使用 HTML 和 Jquery 根据文本修复文本区域高度
问题描述
我需要一个帮助。我需要根据里面写的内容来修复文本区域的高度。我在下面解释我的代码。
<html>
<head>
<link rel="stylesheet" href="lib/style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="lib/script.js"></script>
</head>
<body>
<h1>Hello</h1>
<textarea id="textarea-container">
Line 1
Line 2
Line 3
Line 4
ccccccccccccccccccccc
</textarea>
<script>
var $textArea = $("#textarea-container");
// Re-size to fit initial content.
resizeTextArea($textArea);
// Remove this binding if you don't want to re-size on typing.
$textArea.off("keyup.textarea").on("keyup.textarea", function() {
resizeTextArea($(this));
});
function resizeTextArea($element) {
$element.height($element[0].scrollHeight);
}
</script>
</body>
</html>
这里一些文本存在于文本区域及其滚动中。我在这里需要文本区域的高度将根据其中存在的内容进行扩展,并且不会滚动。
解决方案
我创建了一个简化的示例。它获取元素的scrollHeight
属性textarea
并根据它设置内部高度。overflow-y: hidden
很重要,因为否则scrollHeight
属性是与垂直滚动条一起计算的。
// Set height after page has loaded
adjustTextAreaHeight($('#textarea-container'));
// Attach keydown event
$('#textarea-container').on('keydown', adjustTextAreaHeight);
function adjustTextAreaHeight(ta) {
if (!ta.length) {
ta = $(this);
}
// Get full scroll height of text area element
var scrollHeight = ta.prop('scrollHeight');
// Some browsers do not shrink element, so we set 0 height at first
ta.innerHeight(0)
.innerHeight(scrollHeight);
}
#textarea-container {
overflow-y: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>Hello</h1>
<textarea id="textarea-container">
Line 1
Line 2
Line 3
Line 4
ccccccccccccccccccccc
</textarea>
推荐阅读
- macos - 在 macOS 上的 PhpStorm 中使用非原生全屏窗口模式
- python - 在 Python 中计算与 Pandas 数据框中具有相同名称的行对应的时间
- azure - 利用 Azure 自定义脚本扩展跨多个服务器维护自定义 PowerShell 模块
- excel - 在 Windows 窗体应用程序上使用 VB.NET 检测 Excel 单元格中的删除线
- javascript - 接口中的打字稿静态方法
- sh - Bourne shell:我应该如何在从管道读取的while循环中终止脚本?
- python - 删除字典列表中的回车和换行符 - Python
- android - 实例化匿名接口
- java - 在所有功能场景结束后执行 Cucumber hooks
- spring-boot - spring cloud sleuth 如何将跟踪信息添加到 logback 日志行