在tinyMCE编辑器中,将插入符号移动到单词的末尾

Move caret to the end of a word in a tinyMCE editor

本文关键字:移动 单词 符号 插入 编辑器 tinyMCE      更新时间:2023-09-26

我试图为我的tinyMCE编辑器构建一个函数,该函数在键入时使用span标签包装某些单词,到目前为止,我有这个,我在初始化tinyMCE实例时在init_instance_callback选项中使用:

function(ed) {
        ed.on('keyup', function () {
            var editor     = tinyMCE.get('content'),
                regex      = new RegExp('test|abc', 'gi'),
                oldContent = editor.getContent(),
                newContent = oldContent.replace(regex, '<span style="background-color: yellow;">$&</span>');
            // Save cursor position
            var marker = editor.selection.getBookmark(2);
            // Set new content in editor
            editor.setContent(newContent);
            // Move cursor to where it was
            editor.selection.moveToBookmark(marker);
        });
    }

下面是一个工作示例:http://fiddle.tinymce.com/Jjeaab

它工作得很好,而你正在打字,但只要你输入一个匹配的单词(在这种情况下"测试"或"abc")然后插入符号移动到单词的开头,我相信这是因为我添加额外的字符与span元素,所以书签没有正确设置后,单词被包装,有办法解决这个问题吗?

也许您可以插入一个新的Node而不是替换所有的内容。它将为您管理定位。

您只需要在此之前删除匹配的字符串(我让您检查如何正确执行)。

下面是一个例子:

ed.on('keyup', function () {
    var editor = tinyMCE.get('content'),
    regex = new RegExp('test|abc', 'i');
    var match = editor.getContent().match(regex);
    if (match) {
        // Here remove the "match[1].length" last character
        // Then add the new Node, it will set the cursor just after it
        editor.selection.setNode(editor.dom.create('span', {style : 'background-color: yellow;'}, match[1]));
    }
});

您可能还必须查看您的RegExp以防止匹配您创建的节点(您只想匹配用户键入的字符串->而不是被span标记包围)。