0

コードミラーに「ホットキー」の行を追加しようとしています。通常の場合、<textarea id=code>私は次のことができます insertAtCursor(code,'hello')

function insertAtCursor(textArea,text) 
{
    if (textArea.setSelectionRange)
    {
        textArea.value = textArea.value.substring(0,textArea.selectionStart) + text + textArea.value.substring(textArea.selectionStart,textArea.selectionEnd) + textArea.value.substring(textArea.selectionEnd,textArea.value.length);
    } 
    else if (document.selection && document.selection.createRange) 
    {
        textArea.focus();
        var range = document.selection.createRange();

        range.text = text + range.text;
    }
}

CodeMirrorインスタンスでこれを行うにはどうすればよいですか?

4

2 に答える 2

1
function insertAtCursor(instance, text) {
  instance.replaceSelection(text);
}
于 2012-10-14T21:11:11.147 に答える
1

オートコンプリート用に余分な文字を挿入する小さな例を次に示します。ユーザーが a の入力を開始した場合 (余分な を追加したい場合)、カーソルを 1 つ戻して、直接入力を続けることができるようにします。

editor.on('keypress', function(cm,e){
  console.log("keypress: "+e.charCode);
  if(e.charCode === 40) { //check for ( and autocomplete with ) while placing cursor inside ()
      e.preventDefault(); //ignore this key
      editor.replaceSelection("()"); //replace with ()
      editor.setCursor(editor.getCursor().line,editor.getCursor().ch-1); //set cursor back one position
      return false;
   }
});
于 2015-11-18T13:47:35.657 に答える