问题:
我的javascript中有一个CKEditor实例:
- var editor = CKEDITOR.instances["id_corpo"];
我需要以编程方式插入一些文本,然后选择一些文本范围.
我已经插入了文本
- editor.insertHtml('<h1 id="myheader">This is a foobar header</h1>');
但是我需要通过javascript以编程方式选择(突出显示)“foobar”这个词,以便我可以使用selenium来计算我的CKEditor插件的一些功能测试.
更新1:
我也试过类似的东西
- var selection = editor.getSelection();
- var childs = editor.document.getElementsByTag("p");
- selection.selectElement(childs);
但根本不起作用!
我怎样才能做到这一点?
我觉得
- selection.selectRange()
可以做的工作,但我不知道如何使用它.
那边没有例子:(
解决方法
获取当前选择
- var editor = CKEDITOR.instances["id_corpo"];
- var sel = editor.getSelection();
将选择更改为当前元素
- var element = sel.getStartElement();
- sel.selectElement(element);
将范围移动到您要选择的文本
- var findString = 'foobar';
- var ranges = editor.getSelection().getRanges();
- var startIndex = element.getHtml().indexOf(findString);
- if (startIndex != -1) {
- ranges[0].setStart(element.getFirst(),startIndex);
- ranges[0].setEnd(element.getFirst(),startIndex + findString.length);
- sel.selectRanges([ranges[0]]);
- }