textarea - 防止用户键入多于指定的行

textarea - prevent user to type more lines than specified

我的文本区域是 rows = "3",需要防止用户键入超过 3 行。

此代码阻止键入第四行,但无论如何都会设置该行。

如果已经存在三行,如何防止按 Enter 换行?

$('.tx').on('keypress', function () {
   let max = parseInt($(this).attr('rows'));
   let a = $(this).val();
   let x = a.split("\n").length - 1;
   if(x == max){return false;}
});
.tx{
display:block;
width:100%;
background:gold;
line-height:1.3em;
text-transform:uppercase;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea class='tx' rows = "3"></textarea>

如果按下的键是 Enter 并且当前行数是最大值:

,您应该阻止该事件

$('.tx').on('keypress', function(e) {
  const maxRows = Number($(this).attr('rows'));
  const currRows = $(this).val().split("\n").length;
  if (maxRows === currRows && e.key === 'Enter') {
    e.preventDefault();
  }
});
.tx {
  display: block;
  width: 100%;
  background: gold;
  line-height: 1.3em;
  text-transform: uppercase;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea class='tx' rows="3"></textarea>

请注意,这种技术仅适用于 键入的 字符 - 通过粘贴、单击拖动等方式输入的字符可能仍包含不需要的 \n,因此您可能会用换行符和 slice 拆分为 trim 它们:

$('.tx').on('keypress paste', function(e) {
  setTimeout(() => tryReplace(e.target));
});

function tryReplace(textarea) {
  const maxRows = textarea.rows;
  textarea.value = textarea.value
    .split('\n')
    .slice(0, 3)
    .join('\n');
}
.tx {
  display: block;
  width: 100%;
  background: gold;
  line-height: 1.3em;
  text-transform: uppercase;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea class='tx' rows="3"></textarea>