如果以编程方式设置值,则文本区域自动高度

textarea auto height if value is set programatically

首先我期待 textarea css height:auto 使其真正 height:auto 即匹配内容
很快 - 它不起作用

这是我的 js 制作方法 height:auto
问题 - 只有当我在文本区域内输入时它才有效,如果我通过单击按钮设置值则无效

$('.btx').on('input', function(){
    $(this).css('height', 'auto').height(this.scrollHeight + 'px');
});

$('button').on('click', function(){
  $('.btx').val("lorem\nipsum\ndolor\nsit\namet");
  $('.btx').css('height', 'auto').height(this.scrollHeight + 'px');
});
.btx{
    display:block;
    width:100%;
    resize:none;
    padding:9px 20px;
    line-height:25px;
    font-family:courier;
    overflow:hidden;
    background:orange;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>CLICK</button>
<textarea class='btx'></textarea>

问题是因为在 button 事件处理程序中 this 将是 button,而不是 .btx 元素,所以您正在阅读 scrollHeight 来自错误的地方。

我建议在一个变量中缓存对 .btx 的引用,然后您可以引用该变量以便 set/get 您需要的属性。试试这个:

let $btx = $('.btx').on('input', function() {
  $btx
    .css('height', 'auto')
    .height(this.scrollHeight + 'px');
});

$('button').on('click', function() {
  $btx
    .css('height', 'auto')
    .val("lorem\nipsum\ndolor\nsit\namet")
    .height($btx.get(0).scrollHeight + 'px');
});
.btx {
  display: block;
  width: 100%;
  resize: none;
  padding: 9px 20px;
  line-height: 25px;
  font-family: courier;
  overflow: hidden;
  background: orange;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>CLICK</button>
<textarea class='btx'></textarea>

除了@Rory McCrossan 的回答,由于您已经定义了输入事件,我建议您在单击按钮后触发输入。

$('.btx').on('input', function(){
    $(this).css('height', 'auto').height(this.scrollHeight + 'px');
});

$('button').on('click', function(){
  $('.btx').val("lorem\nipsum\ndolor\nsit\namet");
  $('.btx').trigger('input');
});
.btx{
    display:block;
    width:100%;
    resize:none;
    padding:9px 20px;
    line-height:25px;
    font-family:courier;
    overflow:hidden;
    background:orange;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>CLICK</button>
<textarea class='btx'></textarea>