2016-07-12 50 views
1

末我這樣設置只讀線在我的編輯器:CodeMirror - 檢查光標在行

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

哪裏readOnlyLines是包含行數的數組是隻讀的。

問題是,當我在一個只讀的可編輯行下面,如果我按「刪除」只讀行出現上行,我可以編輯它。

如果我只有一個只讀行,並且按「BackSpace」,這同樣行不通。

我想如果來檢查,如果在同一時間我要補充一個:

  1. 德爾被按下(我用的是抓事件)
  2. 下面的線是隻讀的,(我也用同樣的方式我沒有與如果在上面的代碼)
  3. 光標位於線(的端部是否一個特定的功能存在嗎?)

回答

1

光標位於行的末尾(是否一個特定的功能存在嗎?)

如果(cm.doc.getLine(change.from.line)。長度== change.from.ch){

如果readOnlyLines陣列是你可以做這樣的事情了一系列contigous線:

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

+0

那是不行的,在你的例子,如果我按「Del」從行的末尾0它刪除「換行符「,然後我可以編輯第1行。 – ale93p

+0

@ ale93p你現在可以試試嗎? – gaetanoM

+0

謝謝!現在它可以工作。 – ale93p