我的代码中有一个文本区域,用于显示后端响应的消息。而且我想在内容的长度过长而出现滚动条时自动增加高度。这是我的代码:
$.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还是true,它都显示“ undefined”。设置false并不意味着我要调用的语句必须在函数中的下一条语句可以调用之前完成?我一直对结果感到困惑,这是我认为的特定数字。
然后我尝试使用如下所示的“ input”事件函数:
returnString.on('input',function() {
if (this.clientHeight < thhis.scrollHeight) {
$(this).css('height', 'auto').css('height', this.scrollHeight + (this.offsetHeight - this.clientHeight));
}
});
没有任何改变。
我必须做错什么,但我不知道它在哪里。请告诉我原因,首先感谢您的回答。
[here了解$ .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>