CodeMirror - 检查光标是否在行尾

CodeMirror - Check if cursor is at end of line

我在我的编辑器中设置只读行是这样的:

editor.on('beforeChange', function(cm, change) {
    if (~readOnlyLines.indexOf(change.from.line)) {
        change.cancel();
    }
}

其中 readOnlyLines 是一个包含要只读的行数的数组。

问题是,当我在下面有只读行的可编辑行上时,如果我按 "Del",只读行会出现在上面,我可以编辑它。

如果我在上面有一个只读行并且我按 "BackSpace",同样的方法不起作用。

我想我应该添加一个 if 来同时检查是否:

  1. Del 被按下(我使用了 catch 事件)
  2. 下面的行是只读的(我用上面代码中的 if 做的一样)
  3. 光标在行尾(是否存在特定功能?)

The cursor is at the end of line (Does a specific function exist?)

if (cm.doc.getLine(change.from.line).length == change.from.ch) {

如果 readOnly Lines 数组是一系列连续的行,您可以这样做:

$(function () {
  var editor = CodeMirror.fromTextArea(document.getElementById('txtArea'), {
    lineNumbers: true
  });

  var readOnlyLines = [1,2,3];

  editor.on('beforeChange', function(cm, change) {
    if (~readOnlyLines.indexOf(change.from.line)) {
      change.cancel();
    } else {
      // if you are deleting on the row before the next readonly one
      if ((change.origin == '+delete') && ~readOnlyLines.indexOf(1+change.from.line)) {
        // when you press DEL at the end of current line
        if (cm.doc.getLine(change.from.line).length == change.from.ch) {
          change.cancel();
        }
        // if you are deleting the whole line
        if (cm.doc.getSelection() == cm.doc.getLine(change.from.line)) {
          change.cancel();
        }
        // if the line is empty
        if (cm.doc.getLine(change.from.line).trim().length == 0) {
          change.cancel();
        }
      }
    }
  });
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.16.0/codemirror.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.16.0/codemirror.js"></script>



<textarea id="txtArea">
1111
2222 READ ONLY
3333 READ ONLY
4444 READ ONLY
5555
6666
7777
</textarea>