【问题标题】:How to select text in tinymce editor, if I know it's position in html content?如果我知道它在 html 内容中的位置,如何在 tinymce 编辑器中选择文本?
【发布时间】:2018-07-25 16:49:17
【问题描述】:

这个问题很简单,但我正在努力寻找任何简单的解决方案来让它发挥作用。我正在 Wordpress 中使用 TinyMCE。

假设我在 html 内容中有某个单词的位置,我可以从编辑器中得到这样的位置:

tinymce.activeeditor.getContent();

所以我需要选择这个词并移动到选择(滚动到它)。 例如,如果内容包含这样的内容:

...Bla bla bla some <strong>text</strong> and more text and banana and <img src=.../> more text bla blaa...

您可以在那里看到“香蕉”一词,例如,我想选择它。我知道它的位置,假设它的start_pos = 30,end_pos = 35。不一定是一个词,它可以是一个短语(几个词),但我知道它的位置,所以没有区别。

我需要一种在可视化编辑器(或富编辑器)中选择它的方法,就像我对 textarea 所做的那样(如果文本模式处于活动状态),如下所示:

    // cl_editor_lastfocus is textarea
    cl_editor_lastfocus.setSelectionRange(start, end);

    let charsPerRow = cl_editor_lastfocus.cols;
    let selectionRow = (start - (start % charsPerRow)) / charsPerRow;
    let lineHeight = cl_editor_lastfocus.clientHeight / cl_editor_lastfocus.rows;

    // scroll !!
    cl_editor_lastfocus.scrollTop = lineHeight * selectionRow;
    cl_editor_lastfocus.focus();

有可能吗?据我所知,这里的大多数答案都建议使用此文本选择 textnode,然后设置选择范围。但我不知道我必须选择哪个文本节点,因为我想要的单词可以在文档中的任何位置。另外,我可以通过用跨度包装单词然后选择此跨度节点来做到这一点,但是我不想保留此跨度,何时更改或不需要选择。

【问题讨论】:

    标签: javascript wordpress tinymce selection


    【解决方案1】:

    我猜,在可视模式中进行选择的最简单方法是将字符串包装到 span 中,然后使用 editor.dom.select 选择这个 span。

        // We get editor's content, where 'editor' is a tinymce editor instance
        var content = editor.getContent();
    
        function selectText(start, end) {
        // We have start and end position of the text which we want to select
        // Then we wrap our word or frase between positions into span with unique id
        let content_with_span = content.substring(0, start) + '<span id="'+start+'_'+end+'">' + content.substring(start,end) + '</span>' + content.substring(end, content.length);
        // I keep the original 'content' variable outside, because in my case user can switch between various frases and when we switch to the next selection, we don't want to keep previos span in text
    
        // Return content with span into editor
        editor.setContent(content);
    
        // Create selection
        let selection = tinyMCE.activeEditor.dom.select('span[id="'+ start + '_' +  end + '"]')[0];
    
        // If selection exists, select node and move to it
           if (selection) {
              tinyMCE.activeEditor.selection.select(selection);
              selection.scrollIntoView({behavior: "instant", block: "center", inline: "nearest"});
           }
        }
    

    它对我有用,我希望它对其他人有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多