繁体   English   中英

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

[英]Limit number of characters per line in multiline field

我需要具有TextArea的功能

  1. 每行最多只能包含30个字符
  2. 不想在输入时修剪任何值,一行中大于30的下一个字符需要自动出现在下一行中

在我正在使用的代码下面,但是在粘贴包含30个以上字符的行时,它会修剪下一行第一个字符。

<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);
}

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

   $('#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); 
        }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM