jquery - 如何使用 HTML 和 Jquery 根据文本修复文本区域高度

标签 jquery html css

<分区>

我需要一个帮助。我需要根据其中写入的内容修复文本区域的高度。我在下面解释我的代码。

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

这里一些文本出现在文本区域及其滚动中。我需要这里的文本区域高度将根据其中存在的内容扩展,不超过该高度并且它永远不会滚动。

最佳答案

我创建了一个简化示例。它获取 textarea 元素的 scrollHeight 属性并根据它设置内部高度。 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>

关于jquery - 如何使用 HTML 和 Jquery 根据文本修复文本区域高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50152319/

上一篇:javascript - 需要在 JS 中的每次鼠标悬停时逐渐提高 div 不透明度属性

下一篇:javascript - 有没有办法在最小化浏览器窗口大小的同时修复浏览器宽度/文档宽度? 3个

相关文章:

javascript - 使用 Assetics 后找不到一些 404

javascript - Fancybox 不会使用通过 javascript 传递的内容

jquery - .click 只能与 .css 一起使用一次

javascript - 使用后台 jquery 进行导航

jquery - 惯用的 jQuery 延迟事件(仅在打字短暂暂停后)? (又名计时器/打字表/键盘表)

php - 调整图像大小时它不保持比例?

javascript - 为使用 JQuery 模板插入的新元素创建类似 Accordion 的动画

javascript - 分词 css 选项无效

css - 字体在 Firefox 和 IE 上看起来与在 Chrome 上不同

javascript - 如何实现html多选选项复选框的全选功能?