问题:
我的 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]]);
}
关于javascript - 如何以编程方式在 CKEDITOR 中选择文本范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4401469/