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

时间:2014-06-10 12:04:41

标签: javascript jquery regex tinymce tinymce-4

我正在尝试为我的tinyMCE编辑器构建一个函数,当你输入时,它会使用span标记包装某些单词,到目前为止,我已经在init_instance_callback选项中使用了这个函数。初始化tinyMCE实例:

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

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

1 个答案:

答案 0 :(得分:0)

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

你之前也删除了匹配的字符串(我让你检查一下如何正确地做到这一点)。

以下是一个例子:

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以防止匹配您创建的节点(您希望仅匹配用户键入的字符串 - &gt;不包含span标记)。