首页 > 解决方案 > rangeElement.getStartOffset() 始终为 -1

问题描述

我正在尝试获取 Google 文档中不同 rangeElements 的位置。但结果总是-1。

我做了什么:我将文档的每个标题都放入了它自己的 rangeElement 中,这样它就有了自己的 id。有了这个 id,我想稍后在不同的函数中检索内容和位置。

var doc = DocumentApp.getActiveDocument();
var paragraphs = doc.getBody().getParagraphs();
for (var i = 0; i < paragraphs.length; i++) {
if (paragraphs[i].getType() == DocumentApp.ElementType.PARAGRAPH) {
    var heading = paragraphs[i].asParagraph().getHeading();
    //get only headings
    if (heading == DocumentApp.ParagraphHeading.HEADING1) {
    var title = paragraphs[i].asParagraph().asText().getText();
    if (title != "") {
        //put every headings into its own range, so it has its own id
        var rangeBuilder = doc.newRange().addElement(paragraphs[i]);
        var id = doc.addNamedRange('toc', rangeBuilder.build()).getId();
        // check offset and text of the rangeElement
        var offset = doc.getNamedRangeById(id).getRange().getRangeElements()[0].getStartOffset();
        var text = doc.getNamedRangeById(id).getRange().getRangeElements()[0].getStartOffset();
    }
}

在此示例中, 的输出text始终是正确的标题。所以 rangeElement 的内容似乎是正确的。但 的输出offset始终为 -1。

我接下来要做的是:

doc.setCursor(doc.newPosition(rangeElement.getElement(), rangeElement.getStartOffset()));

但这不适用于 -1 的 StartOffset。

标签: google-apps-scriptgoogle-docs

解决方案


Apps 脚本文档说:getStartOffset() Gets the position of the start of a partial range within the range element. If the element is a Text element and isPartial() returns true, the offset is the number of characters before the start of the range (that is, the index of the first character in the range); in any other case, this method returns -1.

参考:

如果您想在所有文档文本中查找某些文本的偏移量,请尝试此操作。

function findTextOffset(s){
  var s=s || 'Monster';//debug default
  var doc=DocumentApp.getActiveDocument();
  var text=doc.getBody().getText();
  var offset=text.indexOf(s);
  var ui=HtmlService.createHtmlOutput(Utilities.formatString('Find: %s Text: %s Offset: %s',s, text, offset));
  DocumentApp.getUi().showModelessDialog(ui, 'Text Offset');
}

推荐阅读