javascript - 删除文本后调整文本区域大小

标签 javascript html css

如果您编写文本,textarea 的大小会增加,但是当您删除此文本时,什么也不会发生。如果要删除文本,是否可以动态降低 textarea 的高度?

$('textarea').on('input', function() {
  var scrollHeight = parseInt($(this).prop('scrollHeight'));
  $(this).height(scrollHeight);
});
.OuterDiv
{
  width:200px;
  height:300px;
  border:1px solid #000;
  position:relative;
  bottom:0;
}
.text
{
  resize:none;
  width:198px;
  height:45px;
  max-height:145px;
  background-color:rgba(90,90,180,1);
  font-size:16px;
  font-family:Arial;
  overflow-y:auto;
  padding:0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="OuterDiv">
  <textarea class="text" placeholder="Write some text..."></textarea>
</div>

最佳答案

设置 height 样式而不是属性,并使用初始高度以便始终从 45px 开始。

$('textarea').on('input', function() {
    $(this).css('height', "45px");
    $(this).css('height', this.scrollHeight+"px");
});
.OuterDiv
{
  width:200px;
  height:300px;
  border:1px solid #000;
  position:relative;
  bottom:0;
  }
.text
{
  resize:none;
  width:198px;
  height:45px;
  max-height:145px;
  background-color:rgba(90,90,180,1);
  font-size:16px;
  font-family:Arial;
  overflow-y:auto;
  padding:0;
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="OuterDiv">
  <textarea class="text" placeholder="Write some text..."></textarea>
</div>

关于javascript - 删除文本后调整文本区域大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40793321/

相关文章:

javascript - 在页面加载时触发事件而不是 onclick 按钮

javascript - 循环 2 "Loading"背景图片

html - 如何将列表缩放到横向设备高度而不是列表内容高度

html - CSS 问题 : vertically aligning label DIV

html - 如何控制导航栏间距?

android - 来自 iOS 的肖像图像在 Windows 上的浏览​​器中呈现风景

HTMl、CSS - 向我的 div 添加黑色覆盖

javascript - Bootstrap Collapse 组件的初始使用不起作用

javascript - 如何将 Express.js 变量传递给 Jade/Pug 无缓冲代码?

javascript - debounceTime 使表单控件运行两次