如何使用Google Apps for Docs将光标移动到文档的开头?

Dai*_*ney 5 google-docs google-apps-script

我正在使用我的Google文档编写Google Apps脚本脚本,并想知道如何将光标移动到文档的最开头.我最后想要做的只是用一些字符串替换第一行.

Ser*_*sas 8

这很简单,您可以使用此处记录setCursor()方法.

示例代码:

function setCursorToStart() {
 var doc = DocumentApp.getActiveDocument();
 var paragraph = doc.getBody().getChild(0);
 var position = doc.newPosition(paragraph.getChild(0), 0);
 doc.setCursor(position);
}
Run Code Online (Sandbox Code Playgroud)

这会将光标位置设置为文档的开头,但是在你的问题中你说你想在这个位置插入一些数据,那么实际的光标位置是无关紧要的,你可以在那里插入一个字符串而不必移动光标.示例代码:

function insertTextOnTop() {
  var doc = DocumentApp.getActiveDocument();
  var top = doc.getBody().getChild(0);
  top.asParagraph().insertText(0,'text to insert');
  doc.saveAndClose();
}
Run Code Online (Sandbox Code Playgroud)