gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 18:20:57 31 4
gpt4 key购买 nike

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

  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 .

    最佳答案

    对于图像:

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

    关于google-apps-script - 在 Google 文档中以编程方式向前或向后移动光标(轻松),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25194466/

    31 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com