简体   繁体   中英

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

I'm trying to build a function for my tinyMCE editor that wraps certain words with a span tag as you type, so far I have this which I'm using in the init_instance_callback option while initializing the tinyMCE instance:

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);
        });
    }

Here's a fiddle with a working example: http://fiddle.tinymce.com/Jjeaab

It works fine while you're typing but as soon as you enter one of the matched words (in this case "test" or "abc") then the caret moves to the start of the word, I believe this is because I'm adding extra characters with the span element so the bookmark isn't setting properly after the word is wrapped, is there a way to fix this?

Perhaps you can insert a new Node instead of replacing all the content. It will manage the positionning for you.

You just have too remove the matched string before that (I let you check how to do that correctly).

Here is an example :

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]));
    }
});

You may also have to look at your RegExp to prevent matching the node that you created (you want to only match the string typed by the user -> not surrounded by span tag).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM