Word js:如何从开始和结束索引获取Range对象

时间:2017-06-02 12:42:28

标签: office-js office365api office365-apps

基本上我想要的是,我现在有开始和结束索引我想从这个开始和结束索引中获取Range对象。

或者如何从现有范围对象中获取开始和结束索引。

Word.run(function (context) {
    var range = context.document.getSelection();
    range.select();

    return context.sync().then(function () {
       console.log('Selected the range.');
    });  
})
.catch(function (error) {

});

请帮我解决这个问题。

提前致谢。

2 个答案:

答案 0 :(得分:2)

增加Ricky的答案。是的,我们不支持特定的范围索引/坐标,因为这是超级错误。 但是,您可以获得任何对象的开始,结束或整个范围。例如,您可以执行类似document.getSelection(“start”)的操作,它将为您提供选择开头的零长度范围(您也可以执行“结束”,如果您将其留空,则可以获得整个选择范围内)。

基本上所有对象都具有该功能。然后,您可以使用其他范围操作,例如expand。看一下这个例子,它从当前插入点到段落末尾获取句子,只是为了让你了解你可以完成的任务。

希望这会有所帮助。感谢。

function getSentences() {
    Word.run(function (context) {
        // gets the complete sentence  (as range) associated with the insertion point.
        var sentences = context.document
            .getSelection().getTextRanges(["."] /* Using the "." as delimiter */, false /*means without trimming spaces*/);
        context.load(sentences);
        return context.sync()
            .then(function () {
                //  expands the range to the end of the paragraph to get all the complete sentences.
                var sentecesToTheEndOfParagraph = sentences.items[0].getRange()
                    .expandTo(context.document.getSelection().paragraphs
                        .getFirst().getRange("end") /* Expanding the range all the way to the end of the paragraph */).getTextRanges(["."], false);
                context.load(sentecesToTheEndOfParagraph);
                return context.sync()
                    .then(function () {
                        for (var i = 0; i < sentecesToTheEndOfParagraph.items.length; i++) {
                            console.log("Sentence " + (i + 1) + ":"
                                + sentecesToTheEndOfParagraph.items[i].text);
                        }
                    });
            });
    })
        .catch(OfficeHelpers.Utilities.log);
}

答案 1 :(得分:1)

office.js Word.Range对象没有像VSTO Word.Range对象那样的数字起点和终点。在office.js中,要获取文本中特定单词的范围,您可能需要执行以下操作之一,具体取决于您的方案。

  • 使用Range.getRange(rangeLocation)方法。
  • 获取父段落的范围。然后使用Range.getTextRanges(...)方法获取段落中的所有单词范围,然后从返回的集合中选择所需的范围。
  • 使用Range.searchParagraph.search搜索单词。

请参阅Word.Range的参考帮助。