【问题标题】:Change height of a textarea after ajax success functionajax成功功能后更改文本区域的高度
【发布时间】:2020-07-25 21:50:44
【问题描述】:

我的代码中有一个文本区域,用于显示从后端响应的消息。当内容的长度太长以至于出现滚动条时,我想自动增加高度。这是我的代码:

$.ajax({
    type: 'POST',
    async: false,
    url: '/text_translation',
    data: JSON.stringify(data),
    success: function(returnStr) {
        $.each(returnStr,function(item, value) {
            returnString.html(returnString.html() + value + '\n');//show message
        });

        console.log(returnString.clientHeight);//undefined

        //if message too long, increase the height 
        if (returnString.clientHeight < returnString.scrollHeight) {
            returnString.css('height', 'auto').css('height', returnString.scrollHeight + (returnString.offsetHeight - returnString.clientHeight));    
        }

}

一开始,因为ajax是异步的,所以我将“async”设置为“false”,以保证在每个函数之后可以执行更改,但也无法正常工作。我尝试打印clientHeight,无论异步是假还是真,它都显示“未定义”。设置 false 是否意味着我正在调用的语句必须在我的函数中的下一条语句被调用之前完成?我一直对结果感到困惑,我认为这是一个特定的数字。

然后我尝试像这样使用“输入”事件函数:

returnString.on('input',function() {
    if (this.clientHeight < thhis.scrollHeight) {
        $(this).css('height', 'auto').css('height', this.scrollHeight + (this.offsetHeight - this.clientHeight));
    }
});

没有任何改变。

我一定是做错了什么,但我不知道错在哪里。请告诉我原因,先谢谢你的回答。

【问题讨论】:

  • 为什么不干脆做.scrollY{ overflow-y:scroll; }之类的事情?

标签: javascript jquery css ajax auto-increment


【解决方案1】:

看看 here 了解 async 如何与 $.ajax 一起工作,因为您使用的是成功回调,我认为它不会影响您的代码在这种情况下的工作方式。

为了调整文本区域的大小,我发现answer 很有用,并创建了一个函数,您可以在其中传入下面的 textarea 元素。

$("button").click(() => {

  let returnStr = "Test\n\nTest\n\nTest\n\nTest\n\nTest\n\nTest";

  $("textarea").val(returnStr);
  resizeTextareaHeight($("textarea")[0]);
});

function resizeTextareaHeight(textarea) {
  while ($(textarea).outerHeight() < textarea.scrollHeight + parseFloat($(textarea).css("borderTopWidth")) + parseFloat($(textarea).css("borderBottomWidth"))) {
    $(textarea).height($(textarea).height() + 1);
  };
}
textarea {
  overflow-y: hidden;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div>

  <button type="button">Pretend Ajax Call</button>
</div>
<div>


  <textarea></textarea>
</div>

【讨论】:

  • 非常感谢。我发现当我用"$("textarea")[n]" 替换变量"returnString" 时,就可以成功了!!
猜你喜欢
  • 2014-09-19
  • 2014-09-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多