我需要你们的帮助。 我使用的是 textarea,它会通过更改行数自动扩展。 在我的项目中,页面不会重新加载并在提交表单后保持原样。我需要在提交时动态更改行数 (2)。 也可以通过回车发送表格。所以我需要在按下按钮或按下 Enter 键后更改行数。 我已经编写了项目中表单的粗略草图,以便您可以对其进行测试:https://codepen.io/C3La-NS/pen/NagZbr
<form id="NewMessage">
<textarea id="shoutbox-comment" data-min-rows="2"></textarea>
<button id="send_message" type="submit" onclick="chatSubmit();">send</button>
</form>
JS:
// auto-resizing textarea
const textarea = document.getElementById("shoutbox-comment");
textarea.addEventListener("input", function() {
this.rows = 2; // Erm...
this.rows = countRows(this.scrollHeight);
});
function countRows(scrollHeight) {
return Math.floor(scrollHeight / 20); // 20px = line-height: 1.25rem
}
// submit by Enter
$(document).ready(function() {
$("#shoutbox-comment").on("keypress", function(event) {
if (event.keyCode == 10 || event.keyCode == 13) {
event.preventDefault();
chatSubmit();
}
});
});
// submit FORM
function chatSubmit() {
$("#NewMessage").submit();
}
谢谢!
最佳答案
jQuery 提交接受在提交之前触发的回调作为参数,因此,您可以:
$("#NewMessage").submit(function( event ) {
event.preventDefault();
$('#shoutbox-comment').attr('rows', 2);
});
关于javascript - 提交时动态更改行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46503731/