[英]CodeMirror: How to read editor text before or after cursor position
我正在嘗試找到一種方法來測試光標是否在特定字符串之前,然后觸發事件。
我正在嘗試做的示例: 用戶單擊編輯器內的某處, cursorActivity
了cursorActivity
(游標或編輯器已更改)事件,我捕獲事件並測試前6個字符是否與字符串'color:'
匹配'color:'
那么我做點什么吧。
我似乎找不到任何類型的方法,讓你實際上直接從編輯器中讀取,除了捕獲每次鍵入字符或粘貼字符串時觸發的readInput
事件。 這適用於某一點但是當用戶通過鼠標單擊移動光標時失敗。
TL; DR如何在特定字符串后立即檢測光標何時移動?
好吧終於找到了解決方案。 您可以使用editor.doc
檢索實際文檔,它可以讓您獲得光標行和字符位置。 然后,您可以使用editor.doc.getLine(n)
檢索所需的行並比較您的子字符串
這是我的測試用例:
<!-- Create a simple CodeMirror instance -->
<link rel="stylesheet" href="lib/codemirror.css">
<script src="lib/codemirror.js"></script>
<textarea id="myTextarea"></textarea>
<script>
var editor = CodeMirror.fromTextArea(myTextarea, {
lineNumbers: true
});
//Catch cursor change event
editor.on('cursorActivity',function(e){
var line = e.doc.getCursor().line, //Cursor line
ch = e.doc.getCursor().ch, //Cursor character
stringToMatch = "color:",
n = stringToMatch.length,
stringToTest = e.doc.getLine(line).substr(Math.max(ch - n,0),n);
if (stringToTest == stringToMatch) console.log("SUCCESS!!!");
});
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.