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

时间:2014-08-08 00:44:12

标签: google-apps-script google-docs-api

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

  var cursor = DocumentApp.getActiveDocument().getCursor();
  var image = cursor.insertInlineImage(resp.getBlob());

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

我找到Document.newPosition来实现这一目标,但使用它似乎非常复杂。

这是我收集的内容:

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

我开始尝试这样做,但我认为我做错了,因为它太复杂了。是不是有一个简单的功能来向前或向后移动一些元素,如箭头键?


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

  var position = doc.newPosition(cursor.getElement(), cursor.getOffset()+1);
  doc.setCursor(position);

但是,如果向前任意移动光标,则必须考虑cursor.getOffset()+1超过ContainerElement的情况。

1 个答案:

答案 0 :(得分:3)

对于图片:

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

对于文字:

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