小提琴-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());
添加以下代码将光标移动到标签的中心。我也更新了您的代码,请使用下面的链接进行访问
$(".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 });