javascript - 有光标,如何在谷歌文档中插入(不附加)段落

标签 javascript google-apps-script google-docs

我正在为 Google Doc 侧边栏编写一个简单的 google 脚本,我遇到了以下问题:我必须在光标所在的位置插入一些文本

该文本需要是一个段落,因为它是必须与其他文本分开的特定代码。接下来是代码(工作)

function insertText(actionObject) {
  var cursor = DocumentApp.getActiveDocument().getCursor();

  var stringToInsert = "\nblablabla";

  cursor.insertText(stringToInsert);
}

问题是 Google 将 \n 替换为 \r,所以它只是一个换行符,而不是一个段落。这意味着,我的代码可以工作,但从技术 Angular 来看并不像预期的那样。

我不能使用 appendParagraph 函数,因为它总是将它添加到文件末尾(并且可能需要在文件中间添加该段落)。

所以,我必须使用可用于 Body 对象的 insertParagraph(childIndex, paragraph) 方法。但是有了光标,我无法找到一种方法来找出我当前的段落位置并在之前插入一个新的段落......

谁能帮我解决这个问题?

提前致谢!

最佳答案

要插入段落,请使用 insertParagraph(childIndex,text) .

function insertMyText(){
  var myText = 'My Text';
  var doc = DocumentApp.getActiveDocument();
  var body = doc.getBody();
  var cursor = doc.getCursor();
  var element = cursor.getElement();
  var container = element.getParent();
  try {
    var childIndex = body.getChildIndex(container);
    body.insertParagraph(childIndex, myText);
  } catch (e) {
    DocumentApp.getUi().alert("There was a problem: " + e.message);
  }
}

关于javascript - 有光标,如何在谷歌文档中插入(不附加)段落,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44317689/

相关文章:

google-sheets - 非法参数异常 : Trying to set foreign cookie while downloading Google Spreadsheet via API?

javascript - 程序化解构

javascript - 403错误-调用者没有权限

google-apps-script - 在 Google Apps 脚本中设置单元格边框宽度

javascript - 用于清除/删除过滤器的 Google Sheets 脚本

google-apps-script - (Google 文档)是否有可能保护某些细胞不移动?

google-apps-script - 如何在 Apps 脚本中获取 Google 文档中下拉菜单的值?

javascript - 如何判断该方法返回 True 还是 False?

javascript - 是否有类似 Ajax 的 javascript 技术来发送带有自定义方案 url 的请求?

javascript - Jquery 验证插件 - TypeError : $(. ..).validate 不是函数