You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过点击按钮在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 17:27:02