CodeMirror getCursor()不起作用? jQuery Javascript

问题描述 投票:3回答:2

使用CodeMirror。我无法使getCursor()函数正常工作。我有一个附加了codemirror源代码的jsFiddle。

----> 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.


});






});
javascript jquery cursor codemirror
2个回答
6
投票

代码似乎可以正常工作。 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
投票

onCursorActivity不适用于我。This对我有用:

let myCodeMirror = CodeMirror.fromTextArea(myTextArea, {
    lineNumbers: true,
});

CodeMirror.on(myCodeMirror, "cursorActivity", (instance, obj)=>{        
    console.log(instance.doc.getCursor())
}

这将在每次光标更改其位置时记录一个对象,该位置包含line号和ch号。

© www.soinside.com 2019 - 2024. All rights reserved.