Word JS:如何从开始和结束索引获取范围对象



基本上我想要的是,我已经开始和结束索引,现在我想从此开始和结束索引中获取范围对象。

或如何从现有范围对象获得启动和结束索引。

Word.run(function (context) {
    var range = context.document.getSelection();
    range.select();
    return context.sync().then(function () {
       console.log('Selected the range.');
    });  
})
.catch(function (error) {
});

请帮助我如何解决这个问题。

预先感谢。

增强瑞奇的回答。是的,我们不支持特定的范围索引/坐标,因为这是超级错误。但是,您可以获取任何对象的开始,结束或整个范围。例如,您可以执行诸如document.getSelection(" start"(之类的操作范围(。

基本上所有对象都具有该功能。然后,您可以使用其他范围操作(例如Expanding(。查看此示例谁从当前插入点到段落结束的句子,只是为了让您了解您可以完成的工作。

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

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);
}

office.js Word.Range对象没有像vsto word.range对象那样具有数字启动和终点。在office.js中,要获取文本中特定单词的范围,您可能需要做以下操作之一,具体取决于您的场景。

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

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

最新更新