在TinyMCE的编辑器插入文本光标所在(Inserting text in TinyMCE Edi

2019-07-03 19:58发布

I've been trying to insert text into the TinyMCE Editor at the focused paragraph element (<p>) exactly where the cursor is but got no luck!!

var elem = tinyMCE.activeEditor.dom.get('tinymce');
var child = elem.firstChild;
while (child) {
    if (child.focused) {
        $(child).insertAtCaret("some text");
    }
    child = child.nextSibling;
}

If anyone has any idea on how to solve this I'll be very thankful.

Answer 1:

您应该使用命令mceInsertContent 。 见TinyMCE的文档 。

tinymce.activeEditor.execCommand('mceInsertContent', false, "some text");


Answer 2:

The above answer is good, but it is worth pointing out that this can be used to insert any HTML.

For example:

tinymce.activeEditor.execCommand('mceInsertContent', false, " <b>bolded text</b> ");

will insert bolded text at the current cursor location.

Some other interesting observations:

mceInsertRawHTML also works, but tends to put the cursor at the beginning of the current line in my version of tinyMCE, but ymmv.

mceReplaceContent works as well, but in my case did not work well when the cursor was at the end of the current content.

Again, see the documentation for more information.



Answer 3:

如果使用弹出窗口,你可以使用:

tinyMCEPopup.editor.execCommand('mceInsertLink', false, 'some content goes here');

// mceInsertLink插入在当前光标或插入位置的内容。 //如果编辑不专注,插入将在编辑器中的第一行内容。

如果你想插入HTML标签和JavaScript的变量,你可以使用,例如:

<script type='text/javascript'>

    var my_var= "some value";
    var my_var_two = 99;

    tinyMCEPopup.editor.execCommand('mceInsertLink', false, 
                    '<span >[' + my_var + ', ' + my_var_two + ']</span>');       
    tinyMCEPopup.close(); // too close the popup window

</script>

如果你是在一个PHP文件,你可以使用同样的策略,只是使用PHP,而不是JavaScript的,例如:

<script type='text/javascript'>
    tinyMCEPopup.editor.execCommand('mceInsertContent', false, 
               '<span >[' + <?php echo $my_php_var; ?> +']</span>'); 
</script>

您也可以将PHP变量(假设你是在PHP文件)为Javascript变量和编辑内容插入使用它们,例如:

<script type='text/javascript'>

    var my_var= "<?php echo $my_php_var; ?>";
    var my_var_two = "<?php echo $my_php_var_two_or_a_function_call; ?>";

    tinyMCEPopup.editor.execCommand('mceInsertLink', false, 
                     '<span >[' + my_var + ', ' + my_var_two + ']</span>');       
    tinyMCEPopup.close(); // too close the popup window

</script>


文章来源: Inserting text in TinyMCE Editor where the cursor is