【问题标题】:Move cursor programmatically forward or back (easily) in Google Document在 Google 文档中以编程方式向前或向后(轻松)移动光标
【发布时间】:2014-08-08 00:44:11
【问题描述】:

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

  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 的情况。

【问题讨论】:

    标签: google-apps-script google-docs


    【解决方案1】:

    图片:

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

    【讨论】:

    • 你的代码没有定义变量doc,让人难以理解。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-10
    • 2010-10-13
    • 2020-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多