【问题标题】:Append HTML Tag Into Codemirror and Center Cursor Location将 HTML 标记附加到 Codemirror 和中心光标位置
【发布时间】:2014-09-17 20:17:36
【问题描述】:

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

我正在尝试将自定义 html 标签添加到 CodeMirror 并将光标聚焦到这些标签的中心。

Here's 一个文本区域的示例。

// 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;
});

线条和位置总是不同的,所以我必须先抓住它的位置,然后再添加并将其移到添加的字符旁边,就像我在 textarea 演示中所做的那样。

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

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

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

【问题讨论】:

    标签: javascript jquery codemirror cursor-position


    【解决方案1】:

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

    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 });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-28
      • 1970-01-01
      • 1970-01-01
      • 2015-11-20
      • 1970-01-01
      • 2021-09-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多