2013-07-18 27 views
1

使用CodeMirror。我無法使getCursor()函數正常工作。我有一個附帶codemirror源的jsFiddle。CodeMirror getCursor()不工作? JQuery Javascript

---->see here JSfiddle < ----

我想插入文字編輯器,然後強制光標回遷的空間指定數目。我只是試圖用getCursor()獲取光標位置,但我似乎無法讓它工作。有什麼想法嗎?

$(document).ready(function() { 

//Changing the textarea to a CodeMirror rich text editor 

var editor = CodeMirror.fromTextArea(document.getElementById('theZone'), { 
    mode: 'text/html', 
    lineWrapping : true, 
    lineNumbers : true, 
    extraKeys : { 
    "Tab": "indentMore", 
    "Shift-Tab": "indentLess", 
    "'>'": function(cm) { cm.closeTag(cm, '>'); }, 
    "'/'": function(cm) { cm.closeTag(cm, '/'); } 
} , 
onCursorActivity: function(cm) { 
    cm.setLineClass(hlLine, null, null); 
    hlLine = cm.setLineClass(cm.getCursor().line, null, "activeline"); 
} 
}); 


//When SELECT changes - insert the value into the CM editor, set focus, get cursor position, move cursor back [x] amount of spaces. 
$('#sel').change(function() { 
    var selected = $(this).find('option:selected'); 
    var mynum = selected.data('val'); 
    editor.replaceSelection($(this).val(), focus); 
    editor.focus(); 
    var start_cursor = editor.getCursor(); //I need to get the cursor position 
    alert(start_cursor); //Cursor position always comes up [object Object] 

    //write code to move cursor back [x] amount of spaces. [x] is the data-val value. 


}); 






}); 

回答

4

該代碼似乎工作得很好。 alert()不會顯示對象。請改用console.log()。 我添加了其餘的代碼。

$('#sel').change(function() { 
    var selected = $(this).find('option:selected'); 
    var mynum = selected.data('val'); 
    editor.replaceSelection($(this).val(), focus); 
    editor.focus(); 
    var start_cursor = editor.getCursor(); //I need to get the cursor position 
    console.log(start_cursor); //Cursor position 
    var cursorLine = start_cursor.line; 
    var cursorCh = start_cursor.ch; 

    //Code to move cursor back [x] amount of spaces. [x] is the data-val value. 
    editor.setCursor({line: cursorLine , ch : cursorCh -mynum }); 

}); 
+0

哇......沒有意識到這很簡單。謝謝! – Sanya