google-apps-script - 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。
解决方案
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');
}
推荐阅读
- python - 我们如何将字符串更改为整数和浮点数?
- ruby-on-rails - 类方法定义是否会继承单独的单元测试?
- docker - 容器镜像在 Docker Swarm 中运行,但不在 Kubernetes 中
- entity-framework-core - 如何在存储库模式 IdentityDBContext 类中登录 UserID 以覆盖 SaveChanges() 方法?
- javascript - 如何创建一个函数以在单击按钮时传递 ajax 数据
- quarkus - io.quarkus 和 io.quarkus.platform 的区别
- nfc - 使用 Omnikey 5127CK 阅读器阅读 Ultralight C 的第 28 页?
- node.js - 如何强制 docker 容器中的 NodeJs webapp 使用 nginx server_name 而不是 host:port
- c++ - 我可以完全静态链接 MFC 应用程序吗?
- python - 盒子大小不均匀的python热图