javascript – 如何以编程方式选择CKEDITOR中的文本范围?

前端之家收集整理的这篇文章主要介绍了javascript – 如何以编程方式选择CKEDITOR中的文本范围?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
问题:

我的javascript中有一个CKEditor实例:

  1. var editor = CKEDITOR.instances["id_corpo"];

我需要以编程方式插入一些文本,然后选择一些文本范围.

我已经插入了文本

  1. editor.insertHtml('<h1 id="myheader">This is a foobar header</h1>');

但是我需要通过javascript以编程方式选择(突出显示)“foobar”这个词,以便我可以使用selenium来计算我的CKEditor插件的一些功能测试.

更新1:

我也试过类似的东西

  1. var selection = editor.getSelection();
  2. var childs = editor.document.getElementsByTag("p");
  3. selection.selectElement(childs);

但根本不起作用!

我怎样才能做到这一点?

我觉得

  1. selection.selectRange()

可以做的工作,但我不知道如何使用它.
那边没有例子:(

解决方法

获取当前选择
  1. var editor = CKEDITOR.instances["id_corpo"];
  2. var sel = editor.getSelection();

将选择更改为当前元素

  1. var element = sel.getStartElement();
  2. sel.selectElement(element);

将范围移动到您要选择的文本

  1. var findString = 'foobar';
  2. var ranges = editor.getSelection().getRanges();
  3. var startIndex = element.getHtml().indexOf(findString);
  4. if (startIndex != -1) {
  5. ranges[0].setStart(element.getFirst(),startIndex);
  6. ranges[0].setEnd(element.getFirst(),startIndex + findString.length);
  7. sel.selectRanges([ranges[0]]);
  8. }

猜你在找的JavaScript相关文章