如何使用Google Apps Script for Docs将光标移动到文档的开头? [英] How can I move the cursor to the beginning of the document with Google Apps Script for Docs?

查看:114
本文介绍了如何使用Google Apps Script for Docs将光标移动到文档的开头?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am writing a script of Google Apps Script with my Google Document and wondering how to move the cursor to the very beginning of the document. What I was trying to do at the end is just replace the first line with some string.

推荐答案

这很简单,您可以使用 setCursor()方法记录在这里

This is very simple, you can use the setCursor() method documented here.

示例代码:

Example code :

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

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

This will set the cursor position to the start of your document but in your question you say you want to insert some data at this position, then the actual cursor position is irrelevant, you can insert a string there without necessarily moving the cursor . Example code :

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

这篇关于如何使用Google Apps Script for Docs将光标移动到文档的开头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆