2015-04-19 29 views
0

我在側邊欄中有一個按鈕,其目的是在光標位置插入分頁符。我嘗試了腳本來插入一個分頁符(不是在光標處,而是在正文中),它工作正常。谷歌應用程序腳本頁面中斷光標?

不過,我似乎無法得到它的工作光標:

function pageBreak() { 
var cursor = DocumentApp.getActiveDocument().getOffset(); 
insertPageBreak(cursor); 
} 

我怎樣才能做到這一點?

+0

您可以在訪問文檔正文後直接使用'getCursor()'方法。 [這裏是文檔](https://developers.google.com/apps-script/reference/document/document#getCursor())。 – Brian

+0

好的,所以在我使用getCursor()而不是getOffset()之後,如何在光標位置插入/附加分頁符? – arnold

回答

0

您需要知道光標位置處的元素類型。並非所有元素類型都允許插入分頁符。

首先獲取光標位置的元素,然後從那裏開始工作。

function insertPgBrk() { 
    var theCursor = DocumentApp.getActiveDocument().getCursor(); 
    var theElement = theCursor.getElement(); 
    var elementTypeAtCursor = theElement.getType(); 
    Logger.log('elementTypeAtCursor: ' + elementTypeAtCursor); 

    if (elementTypeAtCursor === DocumentApp.ElementType.PARAGRAPH) { 
    Logger.log('its the right type'); 
    theElement.insertPageBreak(0); 
    }; 
}; 

您不能在TEXT元素中插入分頁符。元素需要是段落或LISTITEM。

+0

太棒了,這樣做更有意義。如果我想要在分頁符後的新頁面上添加粗體和居中添加的預定義文本(如「cookies很好」),我該怎麼辦?我是否使用'.editAsText()'或'FontFamily'? – arnold

+0

您可以使用'body.appendParagrah('Cookies are nice')',然後使用[here](https://developers.google.com/apps-script/reference/document/attribute)列出的ENUM值進行設置。 – Brian

+0

現在還不知道。可能會更好地問一個單獨的問題。 –

相關問題