如何通过点击按钮在CodeMirror编辑器的光标位置插入指定文本?
问题原因
CodeMirror初始化后会隐藏原生textarea元素,自行维护编辑内容与DOM渲染,原有针对原生textarea的document.execCommand操作无法作用到CodeMirror的编辑上下文,也无法触发CodeMirror内置的历史记录机制。
解决方案
仅需修改按钮点击事件的逻辑,调用CodeMirror实例自带的API即可实现光标处插入文本,且插入内容自动支持撤销/重做操作,修改后的完整JS代码如下:
var editor = CodeMirror.fromTextArea(document.getElementById("codemirror-highlighter"), { mode: "text/html", theme: "ayu-dark", lineNumbers: true, lineWrapping: true, matchTags: {bothTags: true}, extraKeys: { "Ctrl-J": "toMatchingTag", "Ctrl-Q": function(cm){ cm.foldCode(cm.getCursor()); }, "F11": function(cm) { cm.setOption("fullScreen", !cm.getOption("fullScreen")); }, "Esc": function(cm) { if (cm.getOption("fullScreen")) cm.setOption("fullScreen", false); } }, foldGutter: true, gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"] }); var mapObj = { 'added':' added', 'deleted':' deleted', '(a)':' (a)', '(b)':' (b)', '(c)':' (c)' } jQuery(".cbtn").on("click", function(event) { var currButtonId = jQuery(event.target).attr('id'); var mappedText = mapObj[currButtonId]; // 激活编辑器焦点 editor.focus(); // 在光标当前位置插入文本,自动纳入历史记录支持撤销重做 editor.replaceSelection(mappedText); });
内容的提问来源于stack exchange,提问作者ixcode
相关产品推荐
相关产品推荐

