office-js - Word js : how to get the Range object from start and end index

标签 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) {

});

请帮我解决这个问题。

提前致谢。

最佳答案

补充瑞奇的答案。是的,我们不支持特定范围索引/坐标,因为这非常容易出错。 但是,您可以获得任何对象的开始、结束或整个范围。例如,您可以执行类似 document.getSelection("start") 的操作,这将为您提供选择的开头的零长度范围(您也可以执行“end”,如果将其留空,它将为您提供整个选择范围)。

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

希望这有帮助。谢谢。

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 js : how to get the Range object from start and end index,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44329258/

相关文章:

office-js - 关闭文件并再次打开后,Excel 应用程序中的绑定(bind)是否仍然存在

javascript - 尝试创建日历事件时权限被拒绝 (403)

office-js - 与多个加载项( list )共享自定义功能区

office365 - 能够通过 API 将事件写入只读日历

asp.net-mvc - 将 Office 应用程序与 ASP.NET MVC 连接

asp.net - 是否可以使用 Office 365 API 编辑存储在云中的 Office 文档?

javascript - 在不包含 office.js 的情况下检测 Office 插件主机

outlook-addin - CustomProperties 不会保存在使用 Office.js 的 Outlook 加载项中的定期 session 中

Excel JavaScript API 文件系统交互、系统调用和 API 调用?