Javascript 将HTML标记附加到Codemirror和中心光标位置

Javascript 将HTML标记附加到Codemirror和中心光标位置,javascript,jquery,codemirror,cursor-position,Javascript,Jquery,Codemirror,Cursor Position,小提琴- 我试图将自定义html标记添加到CodeMirror中,并将光标聚焦到这些标记的中心 这是一个如何为textarea执行的示例 // Mirror Codemirror Code to Textarea $(".code").val( editor.getValue() ).on('keyup change', function() { editor.setValue( $(this).val() ); }); // Add center code $(".bold").clic

小提琴-

我试图将自定义html标记添加到CodeMirror中,并将光标聚焦到这些标记的中心

这是一个如何为textarea执行的示例

// Mirror Codemirror Code to Textarea
$(".code").val( editor.getValue() ).on('keyup change', function() {
  editor.setValue( $(this).val() );
});

// Add center code
$(".bold").click(function() {
  // For a regular textarea & center cursor
    var start = $('.code').get(0).selectionStart;
    $('.code').val($('.code').val().substring(0, start) + "<strong></strong>" + $('.code').val().substring($('.code').get(0).selectionEnd));
    $('.code').get(0).selectionStart = $('.code').get(0).selectionEnd = start + 8;
    $('.code').focus();
    return false;
});
//将代码镜像到文本区域
$(“.code”).val(editor.getValue()).on('keyup change',function()){
editor.setValue($(this.val());
});
//添加中心代码
$(“.bold”)。单击(函数(){
//对于常规文本区域和中心光标(&C)
var start=$('.code').get(0).selectionStart;
$('.code').val($('.code').val().substring(0,开始)+“”+$('.code').val().substring($('.code').get(0.selectionEnd));
$('.code').get(0.selectionStart=$('.code').get(0.selectionEnd=start+8;
$('.code').focus();
返回false;
});
行和位置总是不同的,所以我必须先抓取它的位置,然后再添加并将它移到添加的字符旁边,就像我在textarea演示中所做的那样

但是,我不想使用空白文本区域。我想使用Codemirror

我可以毫无问题地添加html标记,但是在附加标记中获取光标位置是我遇到问题的地方

editor.replaceRange("<strong></strong>", editor.getCursor());
editor.replaceRange(“”,editor.getCursor());

添加以下代码以将光标移动到标记的中心。我还更新了你的代码,请使用下面的链接访问它

$(“.bold”)。单击(函数(){
//用于代码镜像和中心光标
editor.replaceRange(“”,editor.getCursor());
editor.focus();
var str=“”;
var mynum=str.length;
var start_cursor=editor.getCursor();//我需要获取光标位置
console.log(开始光标);//光标位置
var cursorLine=start\u cursor.line;
var cursorCh=start\u cursor.ch;
//将光标移回[x]空格量的代码。[x]是数据值。
setCursor({line:cursorLine,ch:cursorCh-mynum});
  $(".bold").click(function() {
    // For codemirror & center cursor
    editor.replaceRange("<strong></strong>", editor.getCursor());
   editor.focus();
    var str="</strong>";
    var mynum=str.length;
    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 });