限制多行字段中每行的字符数

时间:2018-05-15 13:37:54

标签: javascript jquery html textarea

我需要具有TextArea和

的功能
  1. 每行最多30个字符
  2. 不想在输入时修剪任何值,下一行中大于30的字符需要在下一行自动显示
  3. 下面是我正在使用的代码,但在粘贴30多个字符的行时,它会修剪下一行第1个字符。

    <textarea id="textareainput"></textarea>
    
    
    var input= document.getElementById("textareainput");
    var lines = input.value.split("\n");
    var start = input.selectionStart;
    var end = input.selectionEnd;
    
    for (var i = 0; i < lines.length; i++) {
      if (lines[i].length <= 30) continue;
      var j = 0; space = 30;
      while (j++ <= 30) {
        if (lines[i].charAt(j) === " ") space = j;
      }
      lines[i + 1] = lines[i].substring(space + 1) + (lines[i + 1] ? " " + lines[i + 1] : "");
      lines[i] = lines[i].substring(0, space);
    }
    
    input.value = lines.slice(0, lines.length).join("\n");
    
    if (start == end) {
      input.setSelectionRange(start, end);
    }
    

1 个答案:

答案 0 :(得分:0)

尝试以下操作(您的代码稍加更改)

   $('#textareainput').on('input focus keydown keyup', function() {
    var input= document.getElementById("textareainput");
var lines = input.value.split("\n");
var start = input.selectionStart;
var end = input.selectionEnd;

for (var i = 0; i < lines.length; i++) {
  if (lines[i].length <= 30) continue;
  var j = 0; space = 30;
  while (j++ <= 30) {
    if (lines[i].charAt(j) === " ") space = j;
  }
  lines[i + 1] = lines[i].substring(space) + (lines[i + 1] ? " " + lines[i + 1] : "");
  lines[i] = lines[i].substring(0, space);
}

input.value = lines.slice(0, lines.length).join("\n");


});

由于光标定位问题而更新了解决方案:

 function setSelectionRange(input, selectionStart, selectionEnd) {
  if (input.setSelectionRange) {
    input.focus();
    input.setSelectionRange(selectionStart, selectionEnd);
  }
  else if (input.createTextRange) {
    var range = input.createTextRange();
    range.collapse(true);
    range.moveEnd('character', selectionEnd);
    range.moveStart('character', selectionStart);
    range.select();
  }
}

function setCaretToPos (input, pos) {
  setSelectionRange(input, pos, pos);
}
 function formatStr(str, n) {
   var a = [], start=0;
   while(start<str.length) {
      a.push(str.slice(start, start+n));
      start+=n;
   }
  return a.join("\n");
}

$('#textareainput').on('input focus keydown keyup', function() {
    var input= document.getElementById("textareainput");
var lines = input.value.split("\n");
var start = input.selectionStart;
var end = input.selectionEnd;

var v = input.value;
        var vl = v.replace(/(\r\n|\n|\r)/gm,""); //remove all newlines  

        input.value = formatStr(vl,30);

        var lines1 = input.value.split("\n");

        if (start == end)   {
            if(lines1.length!=lines.length)
                setCaretToPos(input, end+1);
            else
            setCaretToPos(input, end); 
        }
});