带有换行符的文本区域maxlength的特征检测

Feature detection for text area maxlength with newlines

本文关键字:maxlength 特征检测 区域 文本 换行符      更新时间:2023-09-26

有充分的文档证明,不同的浏览器对文本区域中的换行符的处理与maxlength有关。例如,如果使用换行符,下面的代码片段在Chrome和Firefox中的表现会有所不同。

我的问题是,我需要允许用户输入换行符,我需要向他们显示他们还剩下多少字符。我可以检测他们的浏览器类型,但这很脆弱,是一种已知的反模式。是否有一种方法可以使用特征检测来正确地做到这一点?还是应该避免maxlength?请注意,我的问题不是特定于jQuery的,我只是在示例中使用了jQuery,以便简单地显示正在发生的事情。请注意,我已经有一个没有maxlength的解决方案的例子(见下面),但它不能很好地在ember等框架中转换,因为你想避免使用jquery hack。

Maxlength问题(尝试使用Firefox, Chrome,并键入至少一个换行符。

$('.t').on('input',function(){
  $('.x').html($('.t').val().length);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea class="t" rows=3 maxlength=10></textarea>
<br>
chars typed: <span class="x"></span>

没有maxlength工作区(gross)

$('.t').on('input', function(){
  let maxLength = 10;
  let val = $('.t').val();
  $('.t').val((val && val.length) ? val.substring(0,maxLength) : val);
  $('.x').html($('.t').val().length);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea class="t" rows=3></textarea>
Chars typed: <span class='x'></span>

您可以使用keydownkeyup事件和正则表达式,它们将用空字符串替换所有新的行字符。在keydown事件中,当到达maxLength时禁止输入新字符,在keyup事件中显示剩余字符数:

var maxLength = 10;
var navKeys = [8,46,27,38,40,33,34,13,37,39];
$(".x").html(maxLength);
$("textarea")
  .on("keydown", function(e){
    // Get value without new lines
    var val = $(this).val().replace(/'n|'r/g, "");
    // Allow nav keys
    if(navKeys.indexOf(e.keyCode) !== -1) {
      return true;
    }
    // Do not allow type in another char
    if(val.length >= maxLength) {
      e.preventDefault();
      return;
    }
  })
  .on("keyup", function(e) {
    // Get value without new lines
    var val = $(this).val().replace(/'n|'r/g, "");
    $(".x").html(maxLength - val.length);
    // Check the max length
    if(val.length > maxLength) {
      $(this).val(val.substr(0,maxLength));
    }
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea></textarea>
<br/>
chars typed: <span class="x"></span>

这对我在FF和Chrome中也是有效的。

我认为最好的选择是你实现自己的maxLength。像这样:

var element = document.getElementById('textarea'),
  maxLength = 10;
var trim = function() {
  if(element.value.length >= maxLength) {
    element.value = element.value.substring(0, maxLength);
  }
};
// for older IE
element.onkeydown = function() {
  setTimeout(trim, 1);
};
// browser support: CH, IE 9+, FF 4.0, SF 5.0, OP
element.oninput = trim;
<textarea rows="3" id="textarea"></textarea>