rangeElement.getStartOffset()始终为-1

时间:2019-01-17 04:02:58

标签: google-apps-script google-docs

我正在尝试获取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()));

但这不适用于StartOffset -1。

1 个答案:

答案 0 :(得分:1)

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.

Reference:

如果您想在所有文档文本中找到某些文本的偏移量,请尝试这样做。

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