在带有书签的索引处将文本插入TinyMCE时丢失选择

时间:2017-01-31 11:39:41

标签: javascript typescript tinymce selection bookmarks

我正在使用Typescript编写代码,我正试图在游标索引处将文本插入到TinyMCE中。我有一个下拉列表,插入了不同的字符串,我想在点击时插入它们。

当我调用此函数两次时,index属性的值为-1,因此我的所有文本都已被删除,似乎书签无法正确恢复选择:

  addCustomTag(tag: string) {
    let bm = this._editor.selection.getBookmark(0);
    let selector = "[data-mce-type=bookmark]";
    let bmElements = this._editor.dom.select(selector);
    this._editor.selection.select(bmElements[0]);
    this._editor.selection.collapse();
    let elementID = "######cursor######";
    let cursorPosition = '<span id="' + elementID + '"></span>';
    this._editor.selection.setContent(cursorPosition);
    let content = this._editor.getContent({ format: "html" });
    let index = content.indexOf(cursorPosition);
    this._editor.dom.remove(elementID, false);
    this._editor.selection.moveToBookmark(bm);

    let tagToInsert = '((' + tag + '))';
    let bookmark = this._editor.selection.getBookmark(0);
    cursorPosition = '<span id="' + bookmark.id + '_start" data-mce-type="bookmark" data-mce-style="overflow:hidden;line-height:0px"></span>';
    content = this._editor.getContent({ format: "html" });
    let part1 = content.substr(0, index);
    let part2 = content.substr(index);
    let contentWithString = part1 + tagToInsert + cursorPosition + part2;
    this._editor.setContent(contentWithString, ({ format: "raw" }));
    this._editor.selection.moveToBookmark(bookmark);
  }

我认为此行存在问题,但我不知道如何修复它:

this._editor.selection.setContent(cursorPosition);
你能帮帮我吗?

先谢谢

编辑:

我找到了一个简单的解决方案来避免我的所有问题:

 addCustomTag(tag: string) {
    this._editor.execCommand('mceInsertContent', false, '((' + tag + '))');
 }

1 个答案:

答案 0 :(得分:0)

我找到了一个简单的解决方案来避免我的所有问题:

 addCustomTag(tag: string) {
    this._editor.execCommand('mceInsertContent', false, '((' + tag + '))');
 }