在 Google 文档中以编程方式向前或向后(轻松)移动光标

Fuh*_*tor 5 google-docs google-apps-script

每当我使用以下代码在文档中插入图像时,

  var cursor = DocumentApp.getActiveDocument().getCursor();
  var image = cursor.insertInlineImage(resp.getBlob());
Run Code Online (Sandbox Code Playgroud)

光标位于图像之前。似乎将光标放在插入的内容之后更有意义,就像它已被粘贴一样。

我发现Document.newPosition可以实现这一点,但使用起来似乎很复杂。

这是我收集的:

  • 获取当前光标
  • 获取它所包含的元素
  • 解析其类型(例如,段落),并根据子项的数量使用 newPosition 处理逻辑,以防光标位于段落末尾等。

我开始尝试这样做,但认为我做错了什么,因为它太复杂了。是否有一个简单的功能可以将光标向前或向后移动一定数量的元素,例如使用箭头键?


编辑:我找到了一个简单的图像插入解决方案。光标后面总是有一个图像,所以这是有效的:

  var position = doc.newPosition(cursor.getElement(), cursor.getOffset()+1);
  doc.setCursor(position);
Run Code Online (Sandbox Code Playgroud)

然而,如果任意向前移动光标,就必须考虑cursor.getOffset()+1超出的情况ContainerElement

Ale*_*x B 5

对于图像:

var cursor = DocumentApp.getActiveDocument().getCursor();
var image = cursor.insertInlineImage(resp.getBlob());
var position = doc.newPosition(image, 1); // image was just inserted, you want to go one cursor position past that.
doc.setCursor(position);
Run Code Online (Sandbox Code Playgroud)

对于文本:

var cursor = DocumentApp.getActiveDocument().getCursor();
var sometext = cursor.insertText("Hokey Pokey");
var position = doc.newPosition(sometext, 11); // Move 11 characters into new text.   You can't move past the end of the text you just inserted.
doc.setCursor(position);
Run Code Online (Sandbox Code Playgroud)

  • 您的代码没有定义变量 doc,这使得它很难理解。 (2认同)