Google Documents:从光标位置获取活动段落

mar*_*omk 3 google-docs google-apps-script

我正在尝试编写一个脚本,将光标周围的文本设置为大写,并将封闭的段落设置为 HEADING1。我能够做第一件事,但我无法弄清楚如何使用 getCursor() 方法获取包含光标的段落。这是我尝试过的:

 var cursor = DocumentApp.getActiveDocument().getCursor();
 var element = cursor.getElement();
 var paragraph = element.asParagraph();
Run Code Online (Sandbox Code Playgroud)

但是,element 是 TEXT 元素,不能转换为 PARAGRAPH。有没有办法从文本元素中获取段落?

谢谢。

Ser*_*sas 6

我花了一些时间,但我明白了;-) Paragraph 是光标周围的 textElement 的父级。

我添加了一些日志,因为我很好奇;-)

function myFunction() {
  var cursor = DocumentApp.getActiveDocument().getCursor();
  var element = cursor.getElement();
  var paragraph = element.getParent().asParagraph();
  var att = paragraph.getAttributes();// optional
  Logger.log(att); // just out of curiosity... if you want to see
  var style = {};
  style[DocumentApp.Attribute.HEADING] =
    DocumentApp.ParagraphHeading.HEADING1;
  paragraph.setAttributes(style);
  var att = paragraph.getAttributes();// optional
  Logger.log(att); // just out of curiosity... if you want to see
  }
Run Code Online (Sandbox Code Playgroud)