简体   繁体   English

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

[英]Append HTML Tag Into Codemirror and Center Cursor Location

Fiddle - http://liveweave.com/kzBlq3小提琴 - http://liveweave.com/kzBlq3

I'm trying to add custom html tags into CodeMirror and focus the cursor into the center of these tags.我正在尝试将自定义 html 标签添加到 CodeMirror 并将光标聚焦到这些标签的中心。

Here's an example of how it'd be done for a textarea.这是一个如何为 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;
});

The lines and locations will always be different so I have to grab it's location first before I add and move it aside the added characters as I did with the textarea demo.线条和位置总是不同的,所以我必须先获取它的位置,然后再添加并将其移到添加的字符旁边,就像我在 textarea 演示中所做的那样。

However I don't want to use a blank textarea.但是我不想使用空白的 textarea。 I want to use Codemirror.我想使用 Codemirror。

I can add the html tag without a problem, but getting the cursor location inside of the appended tag is where I'm having trouble.我可以毫无问题地添加 html 标签,但是在附加标签内获取光标位置是我遇到问题的地方。

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

Add the following code to move cursor to center of tag.添加以下代码以将光标移动到标签中心。 Also I updated your code, Please use the below link for accessing it我还更新了您的代码,请使用以下链接访问它

http://liveweave.com/LLq9GS http://liveweave.com/LLq9GS

  $(".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 });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM