【问题标题】:CodeMirror - Check if cursor is at end of lineCodeMirror - 检查光标是否在行尾
【发布时间】:2016-07-12 16:37:26
【问题描述】:

我以这种方式在我的编辑器中设置只读行:

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

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

问题是,当我在一个可编辑的行上,下面有一个只读行时,如果我按“Del”,只读行会向上,我可以对其进行编辑。

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

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

  1. Del 被按下(我使用了 catch 事件)
  2. 下面的行是只读的(我的做法与上面代码中的 if 相同)
  3. 光标在行尾(是否存在特定函数?)

【问题讨论】:

    标签: javascript jquery readonly codemirror end-of-line


    【解决方案1】:

    光标在行尾(是否存在特定函数?)

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

    如果 readOnlyLines 数组是一系列连续行,您可以执行以下操作:

    $(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>

    【讨论】:

      猜你喜欢
      • 2016-03-26
      • 1970-01-01
      • 2021-03-08
      • 2014-06-03
      • 2011-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多