我需要能够将一串文本更改为 heading1 并稍后进行一些额外的格式化。现在 catch 这部分。这是我目前的示例代码。
function pocket() {
// Try to get the current selection in the document. If this fails (e.g.,
// because nothing is selected), show an alert and exit the function.
var selection = DocumentApp.getActiveDocument().getSelection();
var body = DocumentApp.getActiveDocument().getBody();
if (!selection) {
DocumentApp.getUi().alert('Cannot find a selection in the document.');
return;
}
var selectedElements = selection.getSelectedElements();
var selectedElement = selectedElements[0];
var pocketelement = selectedElement.getElement().getText();
body.appendParagraph(pocketelement).setHeading(DocumentApp.ParagraphHeading.HEADING1);
}
我需要它来删除原始字符串并将段落附加到原始字符串位置。不知道该怎么做。任何帮助将不胜感激!
最佳答案
body.appendParagraph() 方法将给定的段落(如 javascript)附加到正文的末尾。
您正在寻找 .insertParagraph(index, Paragraph)。要获取索引,请尝试 body.getChildIndex(paragraph)。请参阅下面的代码。
function pocket() {
// Try to get the current selection in the document. If this fails (e.g.,
// because nothing is selected), show an alert and exit the function.
var doc = DocumentApp.getActiveDocument();
var selection = doc.getSelection();
var body = doc.getBody();
if (!selection) {
DocumentApp.getUi().alert('Cannot find a selection in the document.');
return;
}
var selectedElements = selection.getSelectedElements();
var selectedElement = selectedElements[0];
//holds the paragraph
var paragraph = selectedElement.getElement();
//get the index of the paragraph in the body
var paragraphIndex = body.getChildIndex(paragraph);
//remove the paragraph from the document
//to use the insertParagraph() method the paragraph to be inserted must be detached from the doc
paragraph.removeFromParent();
body.insertParagraph(paragraphIndex, paragraph).setHeading(DocumentApp.ParagraphHeading.HEADING1);
};
关于javascript - 在特定位置附加段落,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27516995/